Problem with application trying to read data from a network streamwhen the socket is closed

  • Thread starter Nicholas Paldino [.NET/C# MVP]
  • Start date
N

Nicholas Paldino [.NET/C# MVP]

White Spirit,

I find that when it comes to socket-based streams, you can't use stream
readers to do this. They try and buffer bytes from the stream, no matter
what the underlying stream is. Since the socket disconnects, and you call
ReadLine, the StreamReader hangs on the call to Read on the stream, waiting
for the new line combo.

I recommend using the NetworkStream, and reading byte by byte yourself,
parsing apart the new line on your own. If the socket disconnects, then no
more bytes will be returned to you (if the socket is closed).

Hope this helps.
 
W

White Spirit

I have a function within an application where a client connected to a
server continuously sends data. The code on the server side is of the
following form:

Socket socket = receiveSocket;
NetworkStream networkStream = new NetworkStream (socket);
System.IO.StreamReader streamReader = new System.IO.StreamReader
(networkStream);

while (socket.Connected)
{
streamReader.ReadLine();
}

// Do something else when no longer connected


I would like the server to stop reading from the buffer if the client
closes the connection. Instead, the server continues to read blank
lines continuously. No exceptions are thrown. How can I stop this
behaviour and obtain the behaviour that I would like?
 
W

White Spirit

Nicholas said:
I recommend using the NetworkStream, and reading byte by byte yourself,
parsing apart the new line on your own. If the socket disconnects, then no
more bytes will be returned to you (if the socket is closed).

That would solve the problem in terms of program execution. I don't
understand why Socket.Connected wouldn't return false in the example
code, though. In the program I'm writing, it will leave a thread
running unnecessarily and because of the way the data is expected to be
received, I can't use a timeout to close it.
 

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