[.net] TcpClient.GetStream().Read() keeps blocking on server disconnect (solved, own fault)

Started by
4 comments, last by Andrew Russell 18 years ago
The title says it all. I'm using TcpClient to connect to a server. When the server disconnects, NetworkStream.Read keeps on blocking. I can trick it into getting the idea that it's disconnected by sending some data, but I really need a way to do it that doesn't involve sending anything. Any ideas on what is happening and how to fix it? [Edited by - Andrew Russell on May 6, 2006 8:37:42 PM]
Advertisement
This is a problem with TCP – the socket doesn't know it's been closed until you try to use it. You can poll the socket instead using Socket.Available (or NetworkStream.DataAvailable), which will return the amount of data present or throw an exception if the socket is closed.
OK, I tried doing this - I'm afraid it didn't work.

I also saw the Socket.Poll method in there - this didn't do anything either.

[Edited by - Andrew Russell on May 6, 2006 9:15:31 AM]
This is Microsoft's answer..

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemnetsocketsnetworkstreamclassreadtopic.asp


theTroll
What do you mean, 'didn't work'? It should never block, and it also should tell you if data is waiting. Which part didn't do what it should? (Remember you don't call Read unless there is data available!)
Damn.

It turns out it was my own fault. I was losing the return value from Read - so the loop didn't end up exiting if the return value was zero.

Normally an infinate loop like that would be easy to detect - except that Read() would finally throw an exception and cause the loop to exit if data was sent to the disconnected socket.

Thanks for your help, guys.

This topic is closed to new replies.

Advertisement