Search code examples
c#filetask.net-4.5networkstream

NetworkStream truncates my data?


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

Before I start I just want to mention that i'm using those 2 async functions :

For reading 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);
   }

For writing 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 which I know it's size)

enter image description here

My code for sending:

 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 is written :

enter image description here

So where is the problem ?

2.jpg is corrupted ! When I try to open the image I see this :

enter image description here

(instead of a the same image as 1.jpg)

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

I found out that after a while -all it writes are zeros :

larger iamge

enter image description here

Question

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


Solution

  • It looks like your client code does not finish reading the entire content: you should 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 stream chooses to make initially available to you, and stop without retrieving the rest of the bytes.