此
所以我像往常一样在读一条小溪。然后它就卡住了。它不会抛出异常或任何东西。它只是卡住了。
Try
Do
read = stream.Read(datain, 0, datain.Length) 'Stuck here
responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
finalResponse = finalResponse + responseData
Loop While read > 0
Catch ex As Exception
我该怎么做才能让程序永远不会陷入困境?注意,我已经把代码放在try-catch块中了
这是完整的程序。
Public Function getWhoisInfoAsText4(strDomainName As String, whoisServerToTry As String) As String
'testAsisWhois()
Dim data = System.Text.Encoding.ASCII.GetBytes(strDomainName & Microsoft.VisualBasic.vbCr & Microsoft.VisualBasic.vbLf)
Dim finalResponse = String.Empty
Dim client As TcpClient
Try
client = New TcpClient(whoisServerToTry, 43)
Catch ex As Exception
Return ""
End Try
Dim stream = client.GetStream()
Using stream
stream.Write(data, 0, data.Length)
Dim datain = New Byte(254) {}
Dim responseData = String.Empty
Dim read As Integer
Try
Do
read = stream.Read(datain, 0, datain.Length)
responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
finalResponse = finalResponse + responseData
Loop While read > 0
Catch ex As Exception
End Try
End Using
If finalResponse.Contains("Name Server:") Then
appendToTextFile(whoisServerToTry + vbNewLine, "appendfiles", Scripting.IOMode.ForAppending)
End If
finalResponse += (whoisServerUsed + whoisServerToTry + vbNewLine)
Return finalResponse
End Function
您的程序是否停留在第一个循环序列?
根据MSDN mabye的说法,这应该有助于
Dim numBytesRead as Integer = 0
Do
read = stream.Read(datain, numBytesRead, datain.Length)
responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
finalResponse = finalResponse + responseData
numBytesRead += read
Loop While read > 0
Stream.Read总是等待,直到它期望的字节数到来,如果在程序正处于Read的那一刻通信中断,并且连接关闭,则程序将永远在这一点上等待剩余字节的到来,除非您将配置Read Timeout,否则在这段时间内没有接收到任何字节后,它将抛出异常。然后,您应该尝试捕获并重新启动连接。