开发者

data loss when file is transfer from server to client using stream in c#

开发者 https://www.devze.com 2023-01-16 22:09 出处:网络
server side stream.BeginWrite(clientData, 0, clientData.Length, new AsyncCallback(CompleteWrite), stream);

server side

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

client side

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

I have used TCPClient,TCPlis开发者_Python百科tener classes

clientData is a byte array.Size of ClientData is 2682 in server side.I have used NetworkStream class to write data

but in client side received data contains only 1642 bytes.I have used stream class to read data in client side

What's wrong?


The Read method is permitted to return fewer bytes than you requested. You need to call Read repeatedly until you have received the number of bytes you want.


Use this method to read properly from a stream:

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;
 }
}

You may want to Write the length of the file into the stream first (say as an int) eg,

server side:

server.Write(clientData.Length)
server.Write(clientData);

client side:

 byte[] size = new byte[4];                
 ReadWholeArray(stream, size);
 int fileSize = BitConverter.ToInt32(size, 0);
 byte[] fileBytes = new byte[fileSize];
 ReadWholeArray(stream, fileBytes);

see http://www.yoda.arachsys.com/csharp/readbinary.html for more info on reading from streams.

0

精彩评论

暂无评论...
验证码 换一张
取 消