C# 的tcp Socket设置自定义超时时间
C# TCP socket发送大数据包时,接收端和发送端数据不一致 服务端接收Receive不完全
tcp Socket的超时时间默认20多秒,而实际连上不需1秒时间,20多秒是无法接受的。
IPEndPoint ipep = new IPEndPoint(ip, port);//IP和端口 Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ConnectSocketDelegate connect = ConnectSocket; IAsyncResult asyncResult = connect.BeginInvoke(ipep, sock, null, null); bool connectSuccess = asyncResult.AsyncWaitHandle.WaitOne(TimeOut, false); if (!connectSuccess) { MessageBox.Show(string.Format("失败!错误信息:{0}", "连接超时")); return false; } string exmessage = connect.EndInvoke(asyncResult); if (!string.IsNullOrEmpty(exmessage)) { MessageBox.Show(string.Format("失败!错误信息:{0}", exmessage)); return false; } sock.Send(data);//发送信息 reslen = sock.Receive(response, SocketFlags.None);//接收应答数据包
private delegate string ConnectSocketDelegate(IPEndPoint ipep, Socket sock); private string ConnectSocket(IPEndPoint ipep, Socket sock) { string exmessage = ""; try { sock.Connect(ipep); } catch (System.Exception ex) { exmessage = ex.Message; } finally { } return exmessage; }