c# socket通信接收数据包长,不能完整接收的问题
需要用一个socket程序,向网站发送数据包同步接收返回数据包,当网站响应数据短的没有问题,响应数据长的接收不完整。通过抓包发现,响应数据长的超过10个包,但程序只接收了前8个包,超过8个包的后面都没接收成功。大家帮看看问题,附代码:
/// <summary>
/// socket连接发送数据
/// </summary>
/// <param name="p_server"></param>
/// <param name="p_content"></param>
/// <returns></returns>
public string socket(string p_server, string p_content)
{
string m_return = "";
byte[] bytes = new byte[1024*64];
try
{
// Establish the remote endpoint for the socket.
IPHostEntry ipHostInfo = Dns.Resolve(p_server);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 80);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(remoteEP);
///记录向网关发送的记录数据包
///
byte[] msg = Encoding.GetEncoding("utf-8").GetBytes(p_content);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
//m_return = Encoding.ASCII.GetString(bytes, 0, bytesRec);
m_return = Encoding.GetEncoding("utf-8").GetString(bytes, 0, bytesRec);
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
return m_return;
}
catch (ArgumentNullException ane)
{
sender.Close();
return "Error_01";
}
catch (SocketException se)
{
sender.Close();
return "Error_02";
}
catch (Exception e)
{
sender.Close();
return "Error_03";
}
}
catch (Exception e1)
{
return "Error_socket!";
}
return m_return;
}