0

服务器端

stream.BeginWrite(clientData, 0, clientData.Length, 
       new AsyncCallback(CompleteWrite), stream);

客户端

int tot = s.Read(clientData, 0, clientData.Length);

我使用过 TCPClient、TCPlistener 类

clientData 是一个字节数组。ClientData 在服务器端的大小是 2682。我使用 NetworkStream 类写入数据

但在客户端接收到的数据仅包含 1642 字节。我使用流类在客户端读取数据

怎么了?

4

2 回答 2

4

允许 Read 方法返回的字节数少于您请求的字节数。您需要反复调用 Read 直到收到所需的字节数。

于 2010-09-16T11:34:55.763 回答
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

于 2010-09-16T12:12:00.830 回答