views:

263

answers:

1

Following is the code that I'm using for reading data over a .NET socket. This piece of code is run by a single separate thread. It works OK the first time, on the second iteration it stops at "client.Receive(buffer)" and never recovers from it. Initially I was using recursion to read data but changed it to iteration thinking that recursion could be the source of problem. But apparently it is not.

Private Sub ReceiveSocket(ByVal client As Socket)

    Dim bytesRead As Integer = 0

    Do
        bytesRead = client.Receive(buffer)

        sb.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead))

        Array.Clear(buffer, 0, buffer.Length)
    Loop While bytesRead > 0

End Sub 'ReceiveCallback

Why does it hang at Receive?

+1  A: 

Well, that's normal. The Receive() method won't return until the server sends something else. Which it probably doesn't do in your case until you ask it to send something else first. You should only call Receive() again if you didn't get the full server response.

Check the protocol specification. A server usually sends something that lets you tell that the full response was received. Like the number of bytes in the message. Or a special character at the end of the message. Linefeed (vbLf) is popular.

Hans Passant