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

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
 
P

Peter Duniho

[...]
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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top