[轉]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));

}

}

 

方式二:修改注冊表(親測有效)

 

 

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

Value Name:  TcpMaxDataRetransmissions
Data Type: REG_DWORD - Number
Valid Range: 0 - 0xFFFFFFFF
Default: 2 (默認值5 修改為2)

Description: This parameter controls the number of times TCP retransmits an individual data segment (non connect segment)
before aborting the connection. The retransmission time-out is doubled with each successive retransmission on a connection.
It is reset when responses resume. The base time-out value is dynamically determined by the measured round-trip time on the connection.


Value Name:  InitialRttData 
Type: REG_DWORD
Valid Range: 0-65535 (decimal)
Default: 0x5dc (1500毫秒 默認值 0xBB8 (3000 decimal) )
Description: This parameter controls the initial retransmission time-out used by TCP on each new connection. It applies to the connection request (SYN) and to the first data segment(s) sent on each connection.

超時時間大概是2*1.5s
來源 https://support.microsoft.com/en-us/help/170359/how-to-modify-the-tcp-ip-maximum-retransmission-time-out


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM