Search code examples
vb.nettcpstreamstreamreader

vb.net - StreamReader hangs if there is nothing to read


i have this code to read the TCP stream:

  Function checkdata() As String
    Dim Stream As NetworkStream = client.GetStream()
    sr = New StreamReader(Stream)

    Dim s As String = sr.ReadLine() <------------
    Return s
  End Function

Problem is that if there is no new data on the stream, the code hangs on the marked line. Why? how can I solve this?


Solution

  • Can you use the .DataAvailable property of a NetworkStream?

    Function checkdata() As String
        Dim Stream As NetworkStream = client.GetStream()
        If Stream.DataAvailable Then
            Dim SR = New StreamReader(Stream)
            Dim s As String = SR.ReadLine()
            Return s
        Else
            Return Nothing
        End If
    End Function