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

C# 使用c中的流将文件从服务器传输到客户端时数据丢失#,c#,.net,file,network-programming,transfer,C#,.net,File,Network Programming,Transfer,服务器端 stream.BeginWrite(clientData, 0, clientData.Length, new AsyncCallback(CompleteWrite), stream); int tot = s.Read(clientData, 0, clientData.Length); 客户端 stream.BeginWrite(clientData, 0, clientData.Length, new AsyncCallback(Comple

服务器端

stream.BeginWrite(clientData, 0, clientData.Length, 
       new AsyncCallback(CompleteWrite), stream);
int tot = s.Read(clientData, 0, clientData.Length);
客户端

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字节。我使用了stream类在客户端读取数据


怎么了

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

允许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;
 }
}
客户端:
有关读取流的更多信息,请参阅。

使用此方法正确读取流:

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;
 }
}
客户端:
有关从流中读取的更多信息,请参阅。

有两种方法可以解决此问题:首先发送数据大小并读取(查看位转换器),或者读取直到读取0字节(0=EOF),我已使用数据大小检查。我使用ReadWholeArray()方法读取流直到发送数据的大小,但在读取1642字节后,下一个读取下一个剩余数据的调用被阻塞。然后程序没有响应,这时您应该再次检查是否确实在服务器端发送所有2682字节。是否从CompleteWrite方法调用
stream.EndWrite
?有两种方法可以解决此问题:首先发送数据的大小并读取(查看位转换器),或者一直读取,直到读取0个字节(0=EOF),我已检查了数据的大小。我使用ReadWholeArray()方法读取流直到发送数据的大小,但在读取1642字节后,下一个读取下一个剩余数据的调用被阻塞。然后程序没有响应,这时您应该再次检查是否确实在服务器端发送所有2682字节。您是否从CompleteWrite方法调用
stream.EndWrite
?在服务器端编码中,对象服务器是哪个类?因为我将NetworkStream类对象与此代码的方法Write一起使用,它会告诉“方法'Write'不会重载并接受'1'参数”。因此,请告诉服务器对象属于哪个类就像在原始代码示例中一样使用BeginWrite,或者使用Write(clientData,0,clientData.Length),假设clientData是您的字节[]arrayIn服务器端编码的对象服务器是哪个类?因为我将NetworkStream类对象与此代码的方法Write一起使用,它会告诉“方法'Write'不会重载并接受'1'参数”。因此,请告诉服务器对象属于哪个类,就像在原始代码示例中一样使用BeginWrite,或者使用Write(clientData,0,clientData.Length),假设clientData是字节[]数组