轉自:https://www.cnblogs.com/jhlong/p/5622336.htmlhtml
C# 的TCP Socket (異步方式)socket
C# TCP socket發送大數據包時,接收端和發送端數據不一致 服務端接收Receive不徹底tcp
tcp Socket的超時時間默認20多秒,而實際連上不需1秒時間,20多秒是沒法接受的。post
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)
{spa
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.18.165"), 9961);//IP和端口
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);orm
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));
}
}