Re: Problem with application trying to read data from a network stream when the socket is closed



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.


--
- Nicholas Paldino [.NET/C# MVP]
- mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx

"White Spirit" <wspirit@xxxxxxxxxxxxxxxx> wrote in message
news:458045a2$1@xxxxxxxxxxxxxxxxxxxxxxxxx
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?


.



Relevant Pages

  • Re: Converting byte array to Unicode string in C#
    ... wsprintf (szError, TEXT("Allocating socket failed. ... MessageBox (NULL, TEXT ("Server could not be located!"), ... // Send a string from the client socket to the server socket. ... // Get the underlying stream of the client. ...
    (microsoft.public.dotnet.framework.compactframework)
  • NetworkStream with CryptoStream help
    ... If the server sends data using networkStream, ... If the client buffer is small the server sends the message. ... Stream write = new CryptoStream, ...
    (microsoft.public.dotnet.framework)
  • Re: Fundamentals question again guys
    ... I now have a working server client model which is great news. ... Also is this right to open the connection and keep the socket open for the ... listen on that stream for a reply, if none comes close the connection. ...
    (microsoft.public.win32.programmer.networks)
  • Re: Network and Cyrpto Stream help
    ... If the server sends data using networkStream, ... If the client buffer is small the server sends the message. ... Stream write = new CryptoStream, ...
    (microsoft.public.dotnet.framework)
  • Re: socket problem
    ... Note that your server has *already* accepted the connection at this ... The issue is br.readlinereads the input stream only sometimes ... => a php script client through php's socket api's. ...
    (comp.lang.java.help)

Loading