开发者

tcpclient getstream - zero bytes read

I have a tcpclient connection setup capturing a continuous http stream. For some reason after the first few bytes are read, the stream does not get any data for a long time. Is there a problem with my code?

   Dim tclient As TcpClient = New TcpClient(url, "80")
   nstream = tclient.GetStream() 
  If nstream.CanRead Then
              defaultsize = 8000, BUFFER_SIZE = 1024
                Dim bufferread(defaultSize) As Byte
                Dim data As String
                mstring = New StringBuilder
                numbytesread = 0
                Dim timestamp As DateTime = DateTime.Now

                Do
                    numbytesread = nstream.Read(bufferread, 0, BUFFER_SIZE)

                    If numbytesread > 1 Then
                        timestamp = DateTime.Now
                        data = Encoding.UTF8.GetStr开发者_Python百科ing(bufferread, 0, numbytesread)
                        parsingUtilities.appendXMLtoFile(data)
                    End If
                    If DateTime.Now.Subtract(timestamp).TotalSeconds > 60 Then
            'timestamp shows no bytesread for more than 60 seconds, then reconnect
                        Exit Sub
                    End If

                Loop While tclient.Connected
            End If


Firstly, you absolutely should not read character data in this way. You're assuming that your byte array always contains a whole number of characters. You should use a StreamReader instead, which is designed to handle this.

If you absolutely must read directly from the stream, use a single instance of Decoder which can handle these partial characters, buffering them for the next conversion.

Now, you're also requiring that numbytesread > 1 - what if it's exactly 1? Why would you want to ignore that?

It's also not clear what your timestamp is for... isn't the stream going to block indefinitely until it gets some data? Or have you explicitly set it up with a read timeout?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜