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 地址和端口号 AsyncCallback result; IAsyncResult connecResult = socketSend.BeginConnect(point, result, null); connecResult.AsyncWaitHandle.WaitOne(3000,true); //IAsyncResult unconnnectResult = socketSend.EndConnect //socketSend.Connect(point); if(connecResult.IsCompleted) { ShowMsg("Connect successed"); //开启一个新线程不停接受服务器发来的消息 Thread th = new Thread(Receive); th.IsBackground = true; th.Start(); } else { socketSend.Close(); ShowMsg("Connect fallied"); } } catch(Exception ex) { MessageBox.Show(ex.Message); }优化这段代码
时间: 2024-01-03 16:03:50 浏览: 133
这段代码的连接部分存在两个问题,一个是异步回调函数result并没有实现,另一个是连接超时机制不够灵活。
针对第一个问题,可以将异步回调函数result改为lambda表达式或者使用async/await机制,这里给出使用async/await机制的示例代码:
```
private async void btnConnect_Click(object sender, EventArgs 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地址和端口号
//异步连接并等待连接完成
await socketSend.ConnectAsync(point);
ShowMsg("Connect successed");
//开启一个新线程不停接受服务器发来的消息
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
```
针对第二个问题,可以使用CancellationTokenSource来实现更灵活的连接超时机制,示例代码如下:
```
private async void btnConnect_Click(object sender, EventArgs 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地址和端口号
//使用CancellationTokenSource实现超时机制
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();
ShowMsg("Connect timeout");
}
catch (Exception ex)
{
//其他异常
socketSend.Close();
MessageBox.Show(ex.Message);
}
}
```
阅读全文