TcpClient接收数据不全
c#在使用TcpClient一般首发数据如下:
private string Tcp(string senddata)
{
try
{
TcpClient client = new TcpClient();
client.Connect(ip, 6789);
//建立连接服务端的数据流
NetworkStream ns = client.GetStream();
byte[] buffer = Encoding.UTF8.GetBytes(senddata);
ns.Write(buffer, 0, buffer.Length);
int count = 0;
List<byte> ls = new List<byte>();
buffer = new byte[bufferSize];
while (true)
{
count = ns.Read(buffer, 0, buffer.Length);
ls.AddRange(buffer);
buffer = new byte[bufferSize];
if (count < bufferSize)
{
break;
}
}
buffer = ls.ToArray();
string recStr = Encoding.UTF8.GetString(buffer);
client.Close();
return recStr;
}
catch
{
return null;
}
}
这么写小量数据是没有问题的,但是在面对大量数据时,经常会出现接收不全。但是在调试的时候,发现接收是完全的。很是奇怪。
经过多次调试发现,在接收大量数据的时候,特别是超过1k时,一定要使用Thread.Sleep(10)函数,以便cpu有时间来处理数据到缓冲区。
private string Tcp(string senddata)
{
try
{
TcpClient client = new TcpClient();
client.Connect(ip, 6789);
//建立连接服务端的数据流
NetworkStream ns = client.GetStream();
byte[] buffer = Encoding.UTF8.GetBytes(senddata);
ns.Write(buffer, 0, buffer.Length);
int count = 0;
List<byte> ls = new List<byte>();
buffer = new byte[bufferSize];
while (true)
{
count = ns.Read(buffer, 0, buffer.Length);
ls.AddRange(buffer);
buffer = new byte[bufferSize];
if (count < bufferSize)
{
break;
}
Thread.Sleep(10);
}
buffer = ls.ToArray();
string recStr = Encoding.UTF8.GetString(buffer);
client.Close();
return recStr;
}
catch
{
return null;
}
}
赞 (0)