Public Sub Listen()
Try
Dim addr() As IPAddress = Dns.GetHostAddresses(Dns.GetHostName())
Dim IPnum As Integer
For i = 0 To addr.Length - 1
If addr(i).ToString Like "192.168.100.*" Then
IPnum = i
End If
Next
Dim iplocalendpoint As IPEndPoint = New IPEndPoint(addr(IPnum), Netport)
tcpl = New TcpListener(iplocalendpoint)
tcpl.Start()
listernerRun = True
While listernerRun
Dim s As Socket = tcpl.AcceptSocket
Dim remote As String = s.RemoteEndPoint.ToString
Dim stream(1024) As Byte
Try
s.ReceiveTimeout = 10000
Catch ex As Exception
End Try
Dim i As Integer = s.Receive(stream)
ReDim Preserve stream(i - 1)
Dim msg As String = Encoding.UTF8.GetString(stream) '"<" + remote + ">" +
Dim arg As AddMessageEventarge = New AddMessageEventarge()
arg.mess = msg
RaiseEvent OnAddMessage(Me, arg)
End While
Catch ex As Exception
'Throw ex 'My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\错误报告\ClassListenner错误报告.txt", Now & " " & ex.Message & vbNewLine, True)
End Try
End Sub
Public Sub Listen()
Try
Dim addr() As IPAddress = Dns.GetHostAddresses(Dns.GetHostName())
Dim IPnum As Integer
For i = 0 To addr.Length - 1
If addr(i).ToString Like "192.168.100.*" Then
IPnum = i
End If
Next
Dim iplocalendpoint As IPEndPoint = New IPEndPoint(addr(IPnum), Netport)
tcpl = New TcpListener(iplocalendpoint)
tcpl.Start()
listernerRun = True
While listernerRun
Dim s As Socket = tcpl.AcceptSocket
Dim remote As String = s.RemoteEndPoint.ToString
Dim stream(1024) As Byte
Try
s.ReceiveTimeout = 10000
Catch ex As Exception
End Try
Dim i As Integer = s.Receive(stream)
ReDim Preserve stream(i - 1)
Dim msg As String = Encoding.UTF8.GetString(stream) '"<" + remote + ">" +
Dim arg As AddMessageEventarge = New AddMessageEventarge()
arg.mess = msg
RaiseEvent OnAddMessage(Me, arg)
End While
Catch ex As Exception
'Throw ex 'My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\错误报告\ClassListenner错误报告.txt", Now & " " & ex.Message & vbNewLine, True)
End Try
End Sub
[/quote] 对,就是s.ReceiveTimeout这个属性。
“就是说一段时间 s.Receive(stream) 收不到东西就跳出,进行下一次的while循环,这样是吗? ”
对的,这样才会导致你的主程序不会hang住,或者你可以监听到一个Socket出来之后,就马上启动一个线程去做事,在线程里面再去Read data,这样也不会导致阻塞主监听程序。
PS. 怎么突然又从C#跳到VB了。:D