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; }