我要做的是接收从客户端发送的大量字节(大约 5MB 数据)
下面是接收 data(byte[]) 的代码
byte[] receivedBytesRaw = new byte[4000];
//first, initialize network stream
NetworkStream stream = client.GetStream();
//The bytesNeeded is the size of bytes which is a protocol sent by the client side indicating the size of byte which will be sent
int bytesNeeded = 4000;
int bytesReceived = 0;
do
{
int bytesRead = stream.Read(receivedBytesRaw, bytesReceived, bytesNeeded - bytesReceived);
networkValidation.addBytesToList(receivedBytesRaw, ref receivedBytes);
bytesReceived += bytesRead;
} while (bytesReceived < bytesNeeded);
但现在我遇到了一个问题:
每次数据到达时,do while循环第一次循环,返回值(i)为26,然后再次循环,这一次,当它到达时" i = stream.Read(receivedBytesRaw, 0, receivedBytesRaw.Length);"
,程序似乎在等待客户端发送数据和没有反应,还有,当我检查“receivedBytesRaw”时,数据不完整,只收到了前13个字节,字节数组中的剩余空间保持为空,并且stream.DataAvailable为false
为什么服务器端收到不完整的数据?注意:当我尝试发送小数据(字符串)时,没关系
==================================================== ====================
已编辑
下面是发送数据的客户端代码:
private int sendData(byte[] dataSend, string IP, int portNumber)
{
TcpClient clientSide = new TcpClient();
int result = -1;
try
{
clientSide.Connect(IP, portNumber);
}
catch (Exception ex)
{
return 2;
}
NetworkStream netStream = clientSide.GetStream();
if (netStream.CanWrite)
{
byte[] replyMsg = new byte[1024];
netStream.Write(dataSend, 0, dataSend.Length);
netStream.Flush();
result = 0;
}
else
{
result = 1;
}
return result;
}