.net - 在字节模式和异步中重用 NamedPipeServerStream 的正确方法

标签 .net asynchronous named-pipes

我正在设置命名管道服务器并从服务器管道读取...我允许 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

一旦 Pipe 的客户端断开连接,我希望 Pipe 可以重复使用。

我循环的部分 在 mRunning 和连接时,这是我应该做的,还是有更好的方法? (我的阅读代码都发生在连接类内部)

同样在我再次开始等待连接的 block 底部,对吗?

最佳答案

...at the bottom of the block where I BeginWaitForConnection again, is that correct...

不,不是。连接后,NamedPipeServerStream 的实例只是一个Stream 包裹在将服务器连接到特定客户端的管道实例周围。它不是为重复使用而设计的。您的代码应将此实例移交给您的 Connection 对象,该对象应确保在与该客户端的通信完成后将其释放。

要重用客户端连接完成时释放的 mServers 中的“插槽”,您需要在某处实例化一个新的 NamedPipeServerStream 并在其上调用 BeginWaitForConnection .看起来您的 PipeConnection 类可能是实现它的地方。

关于.net - 在字节模式和异步中重用 NamedPipeServerStream 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5495730/

相关文章:

http - 如何使用 Tornado HTTPRequest 发布原始文件

bash - 检查命名管道/FIFO 是否打开写入

c# - 线程与线程启动

c# - JwtToken - 声明名称 JwtTokenTypes.Subject 解析为 ClaimTypes.NameIdentifier,这是为什么以及如何防止?

c# - 显示 .NET Core 中间接引用的包中的类

linux - ffmpeg 可以在中断后恢复从管道读取吗?

.net - 保护 NamedPipes WCF 服务的最简单方法?

.net - 如何将 JQuery 嵌入自定义服务器控件

javascript - 使 Meteor 方法调用在客户端同步

javascript - 尝试在 Reactjs 中实现一个简单的 promise