C# Socket 接受数据不全的处理
由于Socket 一次传输数据有限,因此需要多次接受数据传输。
解决办法一:
int
numberOfBytesRead = 0;
int
totalNumberOfBytes = 0;
do
{
numberOfBytesRead = mySocket.Receive(receivedData,totalNumberOfBytes ,
mySocket.ReceiveBufferSize,SocketFlags.None);
totalNumberOfBytes += numberOfBytesRead;
}
while
(numberOfBytesRead > 0);
解决办法二:
//通过clientSocket接收数据
int receiveLength = 0;
int index = 0;
while (clientSocket.Available > 0)
{ //参数 数据缓存区 起始位置 数据长度 值的按位组合
receiveLength += clientSocket.Receive(result, index, clientSocket.ReceiveBufferSize, SocketFlags.None);
index += receiveLength;
}
return Encoding.GetEncoding("GB18030").GetString(result, 0, index);