WebSocket4Net - 'return' 在 websocket 上收到消息

WebSocket4Net - 'return' Message Received on websocket

我正在使用 WebSocket4Net 将我的 xamarin android 应用程序与服务器通信。我可以从我的应用程序发送和接收消息,但我不知道如何在我的 Send 方法中获取传入消息(在 webSocket_MessageReceived 中接收)。我在谷歌上搜索如何使用回调来实现它,但无法实现它。 感谢任何帮助。

这是我的 WebSocketHelper class:

        private WebSocket webSocket;
        private string outgoingMessage;

        public WebSocketHelper(string url)
        {
            webSocket = new WebSocket(url);
            webSocket.Opened += new EventHandler((sender, e) => webSocket_Opened(sender, e, this.outgoingMessage));
            webSocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(webSocket_Error);
            //webSocket.Closed += new EventHandler(webSocket_Closed);
            webSocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(webSocket_MessageReceived);
        }

        public string Send(string message)
        {
            this.outgoingMessage = message;

            webSocket.Open();

            //Get message received from websocket to return it

            return ""; //TEMP return
        }

        private void webSocket_Opened(object sender, EventArgs e, string message)
        {
            webSocket.Send(message);
        }

        private void webSocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
        {
            string errorMessage = e.Exception.Message;

            //return errorMessage to Send method (not sure), this is secondary
        }

        private void webSocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            string incomingMessage = e.Message;

            //I need to return incomingMessage to Send method
        }

你必须做两件事:

  1. 通过string类型引入一个WebSocketHelper成员 您将从事件处理程序传递字符串值 webSocket_MessageReceived 到另一种方法 (Send)
  2. Send 等到 webSocket_MessageReceived 处理程序 叫。您可以为此使用 AutoResetEvent(它应该在 Xamarin 库中提供 Android)。

请注意 _messageReceivedEvent.WaitOne 会使您的 Send 方法阻塞,因此如果您从 UI 事件处理程序调用此方法,您的 UI 将在 [=19 之前无响应=] 被调用。考虑重新设计此 class,使其使用异步方法(它可以公开 UI 订阅的事件 MessageReceivedEvent...)。

    public class WebSocketHelper : IDisposable
    {
       private string _incomingMessage;
       private AutoResetEvent _messageReceivedEvent = new AutoResetEvent(false);
       ...

       public string Send(string message)
       {
          this.outgoingMessage = message;
          webSocket.Open();
          this._messageReceivedEvent.WaitOne(); 
          return this._incomingMessage; 
       }

       private void webSocket_MessageReceived(object sender, MessageReceivedEventArgs e)
       {
          this._incomingMessage = e.Message;
          this._messageReceivedEvent.Set();
       }

       ...
    }