tcpclient getstream - 零字节读取

问题描述:

我有一个tcpclient连接设置捕获一个连续的http流。出于某种原因,读取前几个字节后,该流很长一段时间不会获取任何数据。我的代码有问题吗?tcpclient getstream - 零字节读取

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.GetString(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 

首先,你绝对不应以这种方式读取字符数据。你假设你的字节数组总是包含整数个字符。您应该使用StreamReader来代替,它旨在处理此问题。

如果你绝对必须直接从流中读取,使用的Decoder一个实例,它可以处理这些部分字符,缓冲它们下一次转换。

现在,你也要求numbytesread > 1 - 如果它恰好是1?你为什么要忽略它?

目前还不清楚你的时间戳是什么...是不是流无休止地阻止,直到它获得一些数据?或者你是否明确地将其设置为读取超时?

+0

感谢您的回复。我不知道如何捕获流,并从另一个prgmmer采取建议..但我会考虑使用streamreader或解码器..哦是的,我记得现在为什么我使用网络流,我无法从tcpclient.getstream读取使用streamreader.What究竟是什么意思的流无限期阻塞和读取超时..我认为,如果我没有得到任何东西在流超过一分钟我需要重新连接。 – vbNewbie 2010-11-03 13:30:11