在下面的代码中,StartSocketListener已作为Thread启动。有时,消息的处理需要足够长的时间才会堆叠一些消息(或者至少看起来是这种情况)。我以为我会接受套接字并用它启动另一个线程。我认为将_HostConnection传递给任务会使MessageFunction线程的并发实例安全。不是这样,它出现了。我经常会遇到两种错误:一种是在_HostReader.ReadString,在那里我要么读过流的末尾,要么只读取一部分流(就好像其他东西消耗了部分一样)。另一个是_HostWriter.Write,我得到“已建立的连接被中止”。很明显我没有获得我所期望的线程安全性吗? [我是C#开发人员,所以VB lambda可能看起来很尴尬:)]
Private Sub StartSocketListener()
Dim _Listener As TcpListener = Nothing
Dim _HostConnection As Socket
Try
_Listener = New TcpListener(IPAddress.Parse(GetIPAddress), _TCPListenerPort)
_Listener.Start()
While _KeepListening
_HostConnection = _Listener.AcceptSocket
Dim MessageFunction = Sub(socket As Socket)
Dim _ClientIP As String = socket.RemoteEndPoint.ToString
Dim _HostSocketStream As NetworkStream = New NetworkStream(socket)
Dim _HostWriter As BinaryWriter = New BinaryWriter(_HostSocketStream)
Dim _HostReader As BinaryReader = New BinaryReader(_HostSocketStream)
Try
Dim _MsgXML As String = _HostReader.ReadString
If _MsgXML.Trim <> "" Then
If _KeepListening Then
Dim _RetXML As String = ProcessMessage(_MsgXML, _ClientIP)
Try
_HostWriter.Write(_RetXML)
Catch ex As Exception
...
End Try
End If
End If
Catch ex As Exception
...
End Try
_HostReader.Close()
_HostWriter.Close()
_HostSocketStream.Close()
socket.Close()
End Sub
Task.Factory.StartNew(Sub() MessageFunction(_HostConnection))
End While
_Listener.Stop()
Catch ex As Exception
....
End Try
End Sub