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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用c#中的流将文件从服务器传输到客户端时数据丢失相关的知识,希望对你有一定的参考价值。

服务器端

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

怎么了?

答案

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

另一答案

使用此方法从流中正确读取:

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

以上是关于使用c#中的流将文件从服务器传输到客户端时数据丢失的主要内容,如果未能解决你的问题,请参考以下文章

在tcp从python服务器传输到c#客户端期间丢失数据

前几条消息在传输到离线的 mqtt 客户端时丢失

CGBTN2107-DAY13总结复习

将数据从一列传输到不同表中的不同列

Postgresql主从配置

postgreSQL主从复制