1. 程式人生 > >[轉]c# winform tcp connect timeout 連線超時設定

[轉]c# winform tcp connect timeout 連線超時設定

轉自: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));

}

}