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)
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:
So where is the problem?
2.jpg
damaged! When I try to open the image, I see the following:
(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:
Question
What am I doing wrong? And how can I fix the code so that it sends the whole file?
source to share
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.
source to share