Is NetworkStream truncating my data?

On the same computer, I have 2 console applications. (client sends file to server)

Before I start, I just want to mention that I use these 2 functions async

:

To read from NetworkStream

:

 public static Task<int> ReadAsync1(this NetworkStream networkStream, byte[] buffer, int offset, int size)
   {
     return Task<int>.Factory.FromAsync(networkStream.BeginRead, networkStream.EndRead, buffer, offset, buffer.Length, networkStream);
   }

      

To write to NetworkStream

:

   public static Task WriteAsync1(this NetworkStream networkStream, byte[] buffer, int offset, int size)
    {
      return Task.Factory.FromAsync(networkStream.BeginWrite, networkStream.EndWrite, buffer, offset, buffer.Length, networkStream);
    }

      

My client code :

(let's take a simple file that I know its size)

enter image description here

My code to send:

 NetworkStream ns = socketForServer.GetStream();
 ns.WriteAsync1(File.ReadAllBytes(@"c:\r\1.jpg"), 0, 1593899);
 ns.Flush();

      

My server code : (reading ...)

byte[] d = new byte[1593899];
networkStream.Read(d, 0, d.Length);
File.WriteAllBytes(@"c:\r\2.jpg",d);

      

Result:

2.jpg

written:

enter image description here

So where is the problem?

2.jpg

damaged! When I try to open the image, I see the following:

enter image description here

(instead of the same image as 1.jpg

)

So, I went to see "HEX" for what is wrong:

I found out that after a while they all write to zeros:

more iamge

enter image description here

Question

What am I doing wrong? And how can I fix the code so that it sends the whole file?

+3


source to share


2 answers


It looks like your client code doesn't finish reading all of the content: you must have a loop that reads to the end before checking the content:

int remaining = d.Length;
int pos = 0;
while (remaining != 0) {
    int add = networkStream.Read(d, pos, remaining);
    pos += add;
    remaining -= add;
}

      



Currently, your code reads as much data as the network thread chooses to make initially available to you, and stops without restoring the rest of the bytes.

+7


source


It's a good idea to read all the bytes at once. You should read the data in blocks, something like this:



buffer = new byte[4096];
int offset = 0;
do {
  int read = networkStream.Read(buffer, offset, buffer.Length - offset);
  offset += read;
} while (read != 0);

      

+3


source







All Articles