[转]c# winform tcp connect timeout 连接超时设置

时间:2022-02-14 09:33:55

转自:https://www.cnblogs.com/jhlong/p/5622336.html

简单的c# TCP通讯(TcpListener)

C# 的TCP Socket (同步方式)

C# 的TCP Socket (异步方式)

C# 的tcp Socket设置自定义超时时间

C# TCP socket发送大数据包时,接收端和发送端数据不一致 服务端接收Receive不完全

tcp Socket的超时时间默认20多秒,而实际连上不需1秒时间,20多秒是无法接受的。

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;
}
private void button5_Click_1(object sender, EventArgs e)
{

IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.18.165"), 9961);//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(2000, false); //2秒后结束
if (!connectSuccess)
{
MessageBox.Show(string.Format("失败!错误信息:{0}", "连接超时"));//2秒后弹出

}

string exmessage = connect.EndInvoke(asyncResult); //此处仍然会卡住20多秒,可注释掉
if (!string.IsNullOrEmpty(exmessage))
{
MessageBox.Show(string.Format("失败!错误信息:{0}", exmessage));

}

}