如何使用system.io.pipes发送请求并获取响应

时间:2011-09-14 16:17:03

标签: named-pipes

我正在尝试编写通过命名管道进行通信的客户端和服务器。我需要客户端能够向服务器发送查询并让服务器发送响应。 Web上用于System.IO.pipes的所有示例要么将单个字符串发送到客户端,要么将单个字符串发送到服务器。我找到了一些如何使用旧的Win32管道执行此操作的示例。但是,我不能用它。

这是我到目前为止所拥有的。我知道这是很多代码。但是,我认为问题可能只是在管道流的构造函数之一。

客户代码

Private Sub cmdSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSend.Click
    Dim strMsg As String = ""
    Dim strRequest As String = "Send Key"
    Dim strErrMsg As String = ""

    PrintText("Creating new pipe client")
    'pipeStream = New NamedPipeClientStream(strPipeName)
    'pipeStream = New NamedPipeClientStream(strPipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None)
    pipeStream = New NamedPipeClientStream(strServerName, strPipeName, PipeDirection.InOut, PipeOptions.None, Security.Principal.TokenImpersonationLevel.None)

    PrintText("Connecting to server")
    pipeStream.Connect()
    pipeStream.ReadMode = PipeTransmissionMode.Message

    PrintText("Sending request")
    'Send Request
    If SendPipeMessage(pipeStream, strRequest, strErrMsg) Then
    Else
        PrintText(strErrMsg)
    End If

    PrintText("Receiving response")
    'Process Response
    If ReadPipeMessage(pipeStream, strMsg, strErrMsg) Then
        PrintText(strMsg)
    Else
        PrintText(strErrMsg)
    End If

    pipeStream.Dispose()
    pipeStream = Nothing

End Sub

Private Function SendPipeMessage(ByRef pipeStream As NamedPipeClientStream, ByVal strMsg As String, ByRef strErrMsg As String) As Boolean
    Dim blnRetVal As Boolean = True
    Dim bytMessage() As Byte = Nothing
    Dim encoding As UTF8Encoding = Nothing

    Try
        encoding = New UTF8Encoding
        bytMessage = encoding.GetBytes(strMsg)
        pipeStream.Write(bytMessage, 0, bytMessage.Length)

    Catch ex As Exception
        blnRetVal = False
        strErrMsg = ex.ToString
    End Try
    Return blnRetVal
End Function


Private Function ReadPipeMessage(ByRef pipeStream As NamedPipeClientStream, ByRef strPipeText As String, ByRef strErrMsg As String) As Boolean
    Dim blnRetVal As Boolean = True
    Dim strTextChunck As String = ""
    Dim intNumBytes As Integer = 0
    Dim intNumChars As Integer = 0
    Dim bytMessage(10) As Byte
    Dim chars(10) As Char
    Dim decoder As Decoder = Nothing

    Try
        decoder = Encoding.UTF8.GetDecoder
        strPipeText = ""
        Do
            strTextChunck = ""
            Do
                intNumBytes = pipeStream.Read(bytMessage, 0, bytMessage.Length)
                intNumChars = decoder.GetChars(bytMessage, 0, intNumBytes, chars, 0)
                strTextChunck = strTextChunck & New String(chars, 0, intNumChars)
            Loop While Not pipeStream.IsMessageComplete
            strPipeText = strPipeText & strTextChunck
        Loop While intNumBytes <> 0

    Catch ex As Exception
        blnRetVal = False
        strErrMsg = ex.ToString
    End Try
    Return blnRetVal
End Function

服务器代码

Private Sub cmdListen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdListen.Click
    bw.RunWorkerAsync()
End Sub

Private Sub bw_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
    Dim strRequest As String = ""

    Dim strErrMsg As String = ""

    bw.ReportProgress(0, "Create new pipe server stream")
    pipeStream = New NamedPipeServerStream(strPipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None)

    'Wait for connection
    bw.ReportProgress(0, "Listening for connection")
    pipeStream.WaitForConnection()

    bw.ReportProgress(0, "Receiving request")
    'Receive Request
    If ReadPipeMessage(pipeStream, strRequest, strErrMsg) Then
        bw.ReportProgress(0, "Request : " & strRequest)
    Else
        bw.ReportProgress(0, strErrMsg)
    End If

    'Get response
    strResponse = GetResponse(strRequest)

    bw.ReportProgress(0, "Sending response")
    'Send Response
    If SendPipeMessage(pipeStream, strResponse, strErrMsg) Then
        bw.ReportProgress(0, "Sent response")
    Else
        bw.ReportProgress(0, strErrMsg)
    End If
    bw.ReportProgress(0, "Done!")

    pipeStream.Disconnect()
    pipeStream.Dispose()
    pipeStream = Nothing

End Sub

Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bw.ProgressChanged
    PrintText(e.UserState)
End Sub

Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
    PrintText(e.Result)
End Sub


Private Function SendPipeMessage(ByRef pipeStream As NamedPipeServerStream, ByVal strMsg As String, ByRef strErrMsg As String) As Boolean
    Dim blnRetVal As Boolean = True
    Dim bytMessage() As Byte = Nothing
    Dim encoding As UTF8Encoding = Nothing

    Try
        encoding = New UTF8Encoding
        bytMessage = encoding.GetBytes(strMsg)
        pipeStream.Write(bytMessage, 0, bytMessage.Length)

    Catch ex As Exception
        blnRetVal = False
        strErrMsg = ex.ToString
    End Try
    Return blnRetVal
End Function

Private Function ReadPipeMessage(ByRef pipeStream As NamedPipeServerStream, ByRef strPipeText As String, ByRef strErrMsg As String) As Boolean
    Dim blnRetVal As Boolean = True
    Dim strTextChunck As String = ""
    Dim intNumBytes As Integer = 0
    Dim intNumChars As Integer = 0
    Dim bytMessage(10) As Byte
    Dim chars(10) As Char
    Dim decoder As Decoder = Nothing

    Try
        decoder = Encoding.UTF8.GetDecoder
        strPipeText = ""
        Do
            strTextChunck = ""
            Do
                intNumBytes = pipeStream.Read(bytMessage, 0, bytMessage.Length)
                intNumChars = decoder.GetChars(bytMessage, 0, intNumBytes, chars, 0)
                strTextChunck = strTextChunck & New String(chars, 0, intNumChars)
            Loop While Not pipeStream.IsMessageComplete
            strPipeText = strPipeText & strTextChunck
        Loop While intNumBytes <> 0

    Catch ex As Exception
        blnRetVal = False
        strErrMsg = ex.ToString
    End Try
    Return blnRetVal
End Function

当我启动客户端时,它挂起在ReadPipMessage()上,服务器挂起在ReceivingRequest()上。如果我终止客户端,服务器会读取客户端发送的请求。但是,由于客户端不再运行,它会在发送响应时发生爆炸。

服务器是否无法在同一连接中发送和接收消息?我认为这就是PipeDirection.InOut的意思。

谢谢,

麦克

1 个答案:

答案 0 :(得分:0)

您可能希望查看WCF的命名管道绑定。有很多关于如何使用它的好例子,例如:http://www.jmedved.com/2010/03/named-pipes-in-wcf/