我正在设置一个命名管道服务器并且我从服务器管道中读取...我允许5个可能的并发连接,并且它们是这样设置的。
Public Sub Start()
Dim i As Integer
While i < mTotalServers
Dim s As New IO.Pipes.NamedPipeServerStream("IPSClient", IO.Pipes.PipeDirection.InOut,
mTotalServers, IO.Pipes.PipeTransmissionMode.Byte, IO.Pipes.PipeOptions.Asynchronous)
i += 1
Dim p As New PipeConnection(s, "Index - " & i)
mServers.Add(p)
s.BeginWaitForConnection(New AsyncCallback(AddressOf ConnectionReceived), p)
End While
End Sub
然后我恢复操作直到收到连接。
Private Sub ConnectionReceived(ar As IAsyncResult)
Try
Dim p As PipeConnection = Nothing
If ar.IsCompleted Then
Diagnostics.Debug.Print("Connection received")
p = CType(ar.AsyncState, PipeConnection)
Dim s As IO.Pipes.NamedPipeServerStream = p.Stream
s.EndWaitForConnection(ar)
Dim conn As Connection = New Connection(p)
While mRunning AndAlso p.Stream.IsConnected
If p.ReadHandle.WaitOne(100) Then
Debug.Print("Set")
Else
'
End If
End While
If mRunning Then
s.BeginWaitForConnection(New AsyncCallback(AddressOf ConnectionReceived), p)
End If
Else
p.Stream.Close()
p.Stream.Dispose()
End If
Catch ex As ObjectDisposedException
' Diagnostics.Debug.Print(ex.ToString)
Catch ex As OperationCanceledException
Diagnostics.Debug.Print(ex.ToString)
Catch ex As IO.IOException
Diagnostics.Debug.Print(ex.ToString)
End Try
End Sub
一旦管道的客户端断开连接,我希望管道可以重复使用。
我正在循环的部分虽然mRunning和连接,这是我应该怎么做,还是有更好的方法? (我的阅读代码全部发生在连接类中)
同样在我再次使用BeginWaitForConnection的块的底部,这是正确的吗?
答案 0 :(得分:1)
at the bottom of the block where I BeginWaitForConnection again, is that correct
不,不是。连接后,NamedPipeServerStream
的实例只是围绕将服务器连接到特定客户端的管道实例的Stream
。它不是为了重复使用而设计的。您的代码应该只将此实例交给您的Connection
对象,这应该确保在与该客户端的通信完成时将其处理掉。
要重用mServers中的“插槽”,当客户端连接完成时释放该插槽,您需要在某处实例化新的NamedPipeServerStream
并在其上调用BeginWaitForConnection
。看起来您的PipeConnection
类可能是实现它的地方。