如何通过(异步)网络通信处理消息响应(VB.NET)

时间:2009-07-20 19:35:22

标签: vb.net multithreading asynchronous networking response

我正在编写一个应用程序,通过网络将消息发送到处理消息的另一台PC并发回回复(例如布尔值或其他一些数据)。我的网络通信子(基于WCF)只是让我能够向另一台PC发送消息并处理任何收到的消息。

问题是收到的任何响应都是由我指定的网络消息事件处理程序子处理的,但我无法将其反馈给要求发送原始消息的子。

为了快速说明,情况是这样的:

Private Function NetSendMessage(ByVal message As String) As Boolean 
    'Send network message to PC with device connected 
    '.... 
    'returns true if message sent 
End Function 

Private Sub NetMessageReceived(ByVal sender As Object, ByVal e As MessageEventArgs) Handles NetComm.OnReceiveMessage 
    'Handles incoming messages 
    '.... 
End Sub 

Private Function MoveForward() As Boolean 
    Return (MoveLeftWheel() And MoveRightWheel()) 
End Function 

Private Function MoveLeftWheel() As Boolean 
    If NetSendMessage("MoveLeftWheel") = False Then Return False 

    'Network message went through, now we need to know if the command was executed, which the remote PC will tell us 
    Return ______  *(here is the trouble-- how do I get the boolean response from the other side as to whether this worked or not?)*
End Function 

Private Function MoveRightWheel() As Boolean 
    If NetSendMessage("MoveRightWheel") = False Then Return False 

    Return ______ 
End Function

我到目前为止所考虑的解决方案比这可能需要的更为复杂。

我的一个想法是添加一个ID号来标识每条消息(另一方将在其响应中包含该消息),然后我将为一个“消息队列”提供一个ArrayList。 NetMessageReceived子将向此ArrayList添加任何新消息,并且任何想要回复的函数将监视队列以查看其响应是否到达。它是这样的:

Private NetMessageQueue as New ArrayList 
Private LatestMessageID as Integer 

Private Sub NetMessageReceived(ByVal sender As Object, ByVal e As MessageEventArgs) Handles NetComm.OnReceiveMessage 
    'Handles incoming messages 
    NetMessageQueue.Add(e.Message.ToString) 
End Sub 

Private Function MoveLeftWheel() As Boolean 
    'Send network message to robot PC 

    Private MyMessageID as Integer = LatestMessageID + 1 

    NetSendMessage(MyMessageID & "|" & "MoveLeftWheel") 

    Do 
            For Each msg As String in NetMessageQueue 
                    If msg.Split("|")(0) = MyMessageID.ToString Then 
                            'This is the response message we're waiting for 
                            Return Boolean.Parse(msg.Split("|")(1)) 
                    End If 
            Next 
    Loop 
End Function 

这似乎是一种非常繁琐/不必要的繁琐方式。我正在思考可能添加一个NetSendReceive函数,比如说MoveRightWheel可以调用; NetSendReceive将调用NetSendMessage,监视消息队列的响应(可能通过委托/ IAsyncResult),然后返回响应消息(到MoveRightWheel,它将等待它)。

这可能有更好的方法 - 任何想法?

1 个答案:

答案 0 :(得分:1)

如果你把所有这些都包在课堂里怎么办?那么这个想法就是你在每个实例中只有一个“NetComm”对象。假设您将该类称为MessagingUtility。无论何时您想发送新消息,您都必须致电

Dim myMessage As New MessagingUtility()
myMessage.NetSendMessage("Hello World")

或类似的东西。

这可以防止在同一时间发送大量其他消息时丢失消息上下文的任何可能性。因为毕竟,你想要的给定消息的每个属性都将整齐地包含在myMessage对象中。