tcp连接接收数据卡死,我循环接收Receive传过来数据每次接收1024个字节,当数据接收到最后会卡死
private object SendServer(string xml)
{
Encoding gbk = Encoding.GetEncoding("GBK");
Byte[] byl = gbk.GetBytes(xml);
string _len = "1" + byl.Length.ToString().PadRight(6, ' ');//根据文档说明 报文前面要有7位数字,第一位是加密否标示,后面6位是报文的长度
Byte[] bytesSent = gbk.GetBytes(_len + xml);
Byte[] bytesReceived = new Byte[1024];
List<byte> lst = new List<byte>();
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ServerUrl), int.Parse(Port));
try
{
using (Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
tempSocket.Send(bytesSent, bytesSent.Length, 0);
int bytes = 0;
while (true)
{
if (!tempSocket.Connected) break;
bytes = tempSocket.Receive(bytesReceived, bytesReceived.Length, 0);
for (int i = 0; i < bytes; i++)
{
lst.Add(bytesReceived[i]);
}
if (bytes == 0) break;
}
return gbk.GetString(lst.ToArray(), 0, lst.Count);
}
else
{
throw new Exception("Error:通讯连接失败!请检查农行客户端是否登录!");
}
}
}
catch (Exception ex)
{
throw ex;
}
}
在传输数据最后接收
如果再while语句中卡死说明你设置的跳出循环的语句有问题,如果传输到文件尾,默认的字节数是0吗?查一下说明
因该是你跳出来得那部分有问题,你可以设置一个绝对一点的条件,还有你的跳出我觉得可以放在for循环里,或者在for循环里设置一个值直到这个值等于接收的长度时跳出。
我调试跟踪过while语句跳出循环是没问题的,bytes = tempSocket.Receive(bytesReceived, bytesReceived.Length, 0); 这句话有问题,如如我有1025个字节,第一次接收1024个字节,bytes 返回的是数是1024,循环还是继续再次接收bytes 返回的是数是1,因不等于1 还会再次循环,在这个循环执行这断语句bytes = tempSocket.Receive(bytesReceived, bytesReceived.Length, 0)的时候就会卡死了