服务器端
stream.BeginWrite(clientData, 0, clientData.Length,
new AsyncCallback(CompleteWrite), stream);
客户端
int tot = s.Read(clientData, 0, clientData.Length);
我使用过TCPClient,TCPlistener类
clientData是一个字节数组。在服务器端,ClientData的大小为2682.I已使用NetworkStream类写入数据
但在客户端接收的数据只包含1642个字节。我使用流类来读取客户端的数据
怎么了?
答案 0 :(得分:4)
允许Read方法返回的字节数少于您请求的字节数。您需要重复调用Read,直到收到所需的字节数。
答案 1 :(得分:0)
使用此方法从流中正确读取:
public static void ReadWholeArray (Stream stream, byte[] data)
{
int offset=0;
int remaining = data.Length;
while (remaining > 0)
{
int read = stream.Read(data, offset, remaining);
if (read <= 0)
throw new EndOfStreamException
(String.Format("End of stream reached with {0} bytes left to read", remaining));
remaining -= read;
offset += read;
}
}
您可能希望首先将文件的长度写入流中(例如作为int) 例如,
server.Write(clientData.Length)
server.Write(clientData);
byte[] size = new byte[4];
ReadWholeArray(stream, size);
int fileSize = BitConverter.ToInt32(size, 0);
byte[] fileBytes = new byte[fileSize];
ReadWholeArray(stream, fileBytes);
有关从流中读取的详细信息,请参阅http://www.yoda.arachsys.com/csharp/readbinary.html。