2011-12-11 76 views
0

我使用下面的代码从服务器获取新闻组:没有收到所有数据与networkstream.read

sendBytes = Encoding.ASCII.GetBytes("LIST active microsoft.public*" & ControlChars.CrLf) 
networkStream.Write(sendBytes, 0, sendBytes.Length) 
Array.Clear(bytes, 0, bytes.Length) 
If networkStream.CanRead Then 
    Do 
     numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length) 
     myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)) 
     intLenMyReadBuf = myReadBuffer.Length 
     intLenComplMsg = myCompleteMessage.Length 
     swWriter.WriteLine("buf len = " & intLenMyReadBuf & ", msg len = " & intLenComplMsg) 
     Loop While networkStream.DataAvailable 
Else 
    Console.WriteLine("Sorry. You cannot read from this NetworkStream.") 
End If 

sendBytes = Encoding.ASCII.GetBytes("QUIT " & ControlChars.CrLf) 
networkStream.Write(sendBytes, 0, sendBytes.Length) 
tcpClient.Close() 
networkStream.Close() 

当我执行的代码,程序只接收一个数据块。但是,如果我在循环指令中使用带有断点的 调试模式,则会收到所有数据块。
我是否在代码中遗漏了一些东西,比如等待什么东西,这会让程序
接收调试时发生的所有数据?

回答

1

问题是,你正在循环,直到networkStream.DataAvailable不正确。在正在运行的应用程序中,您的循环可能执行得太快以至于发件人没有时间再次填充缓冲区。

您需要循环直到满足特定条件。例子:

1)所有你期待已接收到的数据的

2)特定的组已收到

3)特定的时间已经达到极限数据(即EOF)的(即如果你30秒内没有收到任何数据,保释)。如果你处于一个无限循环,你应该始终执行这样的事情,除非你打算让这个过程永远持续下去。

我会处理更改为类似:

Dim fLoopDone As Boolean 
' Initialize the timestamp for the last data that was read so that we wait up to 30 seconds 
' at the start for data. 
Dim dtLastData As DateTime = Date.Now 
Do 
    ' Only process the data if there is some available. 
    If networkStream.DataAvailable Then 
     numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length) 
     myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead)) 
     intLenMyReadBuf = myReadBuffer.Length 
     intLenComplMsg = myCompleteMessage.Length 
     swWriter.WriteLine("buf len = " & intLenMyReadBuf & ", msg len = " & intLenComplMsg) 

     ' Record the last time that we received data 
     dtLastData = Date.Now 

     ' Possibly add a check in here to see if you are done reading. 
    Else 
     ' If more than 30 seconds has elapsed since the last data arrived, break out of the loop 
     If Date.Now.Subtract(dtLastData).TotalSeconds > 30 Then 
      fLoopDone = True 
     End If 
    End If 
Loop While Not fLoopDone 
+0

谢谢您的答复competent_tech。我从你的评论中学到了很多,现在我的程序运行得更好。 – Kool

+0

@Kool:非常欢迎您,欢迎来到StackOverflow。请记住,如果您在本网站上回答您的问题可以帮助您解决问题,请点击问题旁边的复选标记和向上箭头,让未来的访问者知道该答案已解决或帮助您解决问题。 –