0

我正在编写一个应用程序,通过网络将消息发送到另一台处理消息并发送回回复(例如布尔值或其他一些数据)的 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 号来标识每条消息(另一方将在其响应中包含该 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)。

可能有更好的方法来做到这一点 - 有什么想法吗?

4

1 回答 1

1

如果您将所有这些都包装在一个类中怎么办?然后的想法是每个实例中只有一个“NetComm”对象。假设您调用了 MessagingUtility 类。每当您想发送新消息时,您都必须致电

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

或类似的东西。

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

于 2009-07-20T21:19:25.730 回答