使用c#中的流将文件从服务器传输到客户端时数据丢失

问题描述 投票:0回答:2

服务器端

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个字节。我使用流类来读取客户端的数据

怎么了?

c# .net file network-programming transfer
2个回答
4
投票

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


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

© www.soinside.com 2019 - 2024. All rights reserved.