Help - NetworkStream blocking read method hangs if client closes the connection


I think the title explains my problem. I have a very basic tcp/ip server (code below) which uses the networkstream read method to read data from the connection. If the client unexpectedly closes the connection the blocking read simply hangs. How do I fix this please? There does not seem to be a timeout property on the read method. I have seen there is a dataavailable property on the network stream class but I do not understand how to use it. I have read the microsoft documentation ( and looked at the example but I am still not clear. What exactly does this mean (taken from microsoft page) "If DataAvailable is true, a call to Read will return immediately" I understand that the read method will complete straight away if data is available. What if there is no data available? Will the method return false and then stop reading data? Could this cause a problem is there is some sort of delay sending the data over the network, even by a second or something?

Many thanks for your help


Dim port As Int32 = 8002
 Dim localAddr As IPAddress = IPAddress.Parse("")
            Dim server As New TcpListener(localAddr, port)

            While True
                Dim client As TcpClient = server.AcceptTcpClient

                Dim bytes(1024) As [Byte]
                Dim data As [String] = Nothing
                    Dim stream As NetworkStream = client.GetStream()
                    Dim i As Int32
                    i = stream.Read(bytes, 0, bytes.Length)
                    While (i <> 0)
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
                    i = stream.Read(bytes, 0, bytes.Length)
                    End While
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Alexandre SimõesManager / Solutions ArchitectCommented:
What is the value of the TimeOut on the TcpClient?
Did you tryed to decrease it?

Alex :p

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Before doing the Read, put it in an If..Then that will checks data availability before doing a read. Did you try these:

For a simple UDP client and server:

Another approach:
You can use the DataAvailable property to check for new incoming data as well as checking if the remote host has closed the connection. Don't do blocking reads on the NetworkStream. Because when you call read, it assumes that there is something to read and won't do enything else, like checking the socket status.

The DataAvailable property will return false as long there is no incoming data and the connection was not closed by the remote host.

Do a read only if the DataAvailable is True. If more than 0 bytes were read, process the received data as usual. If the read then returns 0 bytes read, then you know that the remote host has closed the connection. Note you must close the stream and cilent also on your side when the remote host closes the connection.
Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

andiejeAuthor Commented:
Thank you everyone for your replies.

Zamba1, a question for you please. You said "Do a read only if the DataAvailable is True. If more than 0 bytes were read, process the received data as usual. If the read then returns 0 bytes read, then you know that the remote host has closed the connection. " 

If dataAvailable returns true, how can the read method return 0 bytes? If there wasn't any data for some reason, wouldn't the read method hang?

Also, i probably should have mentioned that my tcp clients send data every 15 seconds so I do need to be able to sit and wait for incoming data. Hpwever, I need to be able to tell if the remote connection has been closed. How can i tell if the remote connection has been closed?

many thanks
andiejeAuthor Commented:

Given my needs it seems by best best is to set the ReceivedTimeout property on the TCPClient. I am not entirely sure how I missed this property!

Thanks very much everyone
Although the answer was already accepted, I will try to answer that above question.

In the case that the remote host closed the connection, DataAvailable will always be true and the read method returns immediately with 0 bytes read. This is the special case about reading from sockets and you must handle this case also. At the same time this is the solution to the question how to tell if the remote connection has been closed.

A simple thread outline would look like this:(after accepting the client)

while true
      if data available
            bytesRead = stream.Read(buffer)
            if bytesRead = 0 then
                  close stream
                  close socket
                     exit while
                  response = ProcessRequest(buffer)
            end if
      end if
end while
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.