NetworkStream.Close() - Last bit of data not being sent

  • Thread starter Thread starter Tom
  • Start date Start date
T

Tom

Hello,

This is my first post on google groups btw :)

I am having an issue with the NetworkStream object.

byte[] buffer = new byte[1024];
int bytesRead = 0;
Networkstream ns = new networkstream(socket);


while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ns.Write(buffer, 0, bytesRead);
ns.Flush();
}

ns.Close(); // <- The Issue

This snippet for some reason does not send all the data in the
buffer.
If I remove the last line "ns.Close();" it works perfectly but causes
other problems such as clients never getting disconnected.

I notice there was a timeout option but I am unsure how how to use it
correctly. How do I determine the time needed to send all the data?
Also shouldn't the Flush() write to the stream.

What this is for is a basic webserver. I browser requests a specific
file and I load it and send it to them. That is what the outcome is
supposed to be.

Any help would be appreciated!

Thanks,

Thomas
 
[...]
This snippet for some reason does not send all the data in the buffer.
If I remove the last line "ns.Close();" it works perfectly but causes
other problems such as clients never getting disconnected.

You need to Shutdown(), and not Close() until you're sure you're done (you
get notification that the connection has been closed).
 
Back
Top