Socket的连接超时时间?
1.使用BeginConnect方法 IAsyncResult connResult = mySocket.BeginConnect(yourAddress, yourPort, null, null); connResult.AsyncWaitHandle.WaitOne(2000, true); //等待2秒 if (!connResult.IsCompleted) { mySocket.Close(); //处理连接不成功的动作 } else { //处理连接成功的动作 } 这种方法很好的控制了连接超时时间而且代码非常简单,但是界面仍然会有2秒的卡死产生。
如果想解决该问题,则需要创建一个额外的线程来执行WaitOne方法。2.使用ConnectAsync方法 SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.Completed += new EventHandlerCopyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有