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

时间:2015-04-23 23:34:04

标签: c# websocket

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

这是在我的WebSocketHelper类中:

        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 个答案:

答案 0 :(得分:2)

你必须做两件事:

  1. 通过引入WebSocketHelper类型的string成员 你将从事件处理程序传递字符串值 webSocket_MessageReceived另一种方法(Send
  2. Send等到webSocket_MessageReceived处理程序 调用。您可以使用AutoResetEvent(它应该在适用于Android的Xamarin库中提供)。
  3. 请注意_messageReceivedEvent.WaitOne使您的Send方法阻止,因此如果您从UI事件处理程序调用此方法,则在调用_messageReceivedEvent.Set之前,您的UI将无响应。考虑重新设计这个类,以便它使用异步方法(它可以公开订阅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();
           }
    
           ...
        }