private async void Btn_start_Click(object sender, RoutedEventArgs e) { try { //负责通信的Socket socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse(txtSever.Text);//拿到本机IP地址 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//连接的IP地址和端口号 //获得要连接的远程服务器应用程序的IP 地址和端口号 //使用CancellationTakenSource实现超时机制 using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3))) { await socketSend.ConnectAsync(point).WaitAsync(cts.Token); } ShowMsg("Connect successed"); //开启一个新线程不停接受服务器发来的消息 Thread th = new Thread(Receive); th.IsBackground = true; th.Start(); } catch (OperationCanceledException ex) { socketSend.Close(); MessageBox.Show(ex.Message); } catch (Exception ex) { socketSend.Close(); MessageBox.Show(ex.Message); } } /// <summary> /// 不停的接收从服务器发来的消息 /// </summary> void Receive() { try { while (true) { byte[] buffer = new byte[1024];//1024*1024*2 int r = socketSend.Receive(buffer); string s = Encoding.UTF8.GetString(buffer, 0, r); ShowMsg(socketSend.RemoteEndPoint + ":" + s); int intRecData = int.Parse(s); Chart.Data = intRecData; mybtn.BtnData = buffer; } } catch(Exception ex) { ShowMsg(ex.Message); MessageBox.Show(ex.Message); }优化这段代码
时间: 2024-01-13 10:03:17 浏览: 70
aa.rar_CSharp Socket_socket
这段代码可以进行如下优化:
1. 将 `Btn_start_Click` 方法中的异常处理部分提取出来,放到一个单独的方法中进行处理,可以避免代码冗余。
2. 将 `socketSend` 的创建和连接操作放到 `using` 块中,这样可以确保 `socketSend` 在使用完之后自动关闭。
3. 将 `Receive` 方法的异常处理部分提取出来,放到一个单独的方法中进行处理,可以避免代码冗余。
4. 在 `Receive` 方法中,如果发生异常,应该关闭 `socketSend`,避免资源泄露。
经过上述优化,代码如下所示:
```
private async void Btn_start_Click(object sender, RoutedEventArgs e)
{
try
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)))
{
await ConnectAsync(cts.Token);
}
ShowMsg("Connect successed");
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start();
}
catch (Exception ex)
{
HandleException(ex);
}
}
private async Task ConnectAsync(CancellationToken cancellationToken)
{
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(txtSever.Text);
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
await socketSend.ConnectAsync(point).WaitAsync(cancellationToken);
}
void Receive()
{
try
{
while (true)
{
byte[] buffer = new byte[1024];
int r = socketSend.Receive(buffer);
string s = Encoding.UTF8.GetString(buffer, 0, r);
ShowMsg(socketSend.RemoteEndPoint + ":" + s);
int intRecData = int.Parse(s);
Chart.Data = intRecData;
mybtn.BtnData = buffer;
}
}
catch (Exception ex)
{
socketSend.Close();
HandleException(ex);
}
}
private void HandleException(Exception ex)
{
socketSend?.Close();
MessageBox.Show(ex.Message);
ShowMsg(ex.Message);
}
```
注意,在 `HandleException` 方法中,需要先判断 `socketSend` 是否为 null,避免在连接前就发生异常时出现空指针异常。
阅读全文