gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:49 25 4
gpt4 key购买 nike

我正在使用 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. 通过string引入WebSocketHelper成员您将从事件处理程序传递字符串值webSocket_MessageReceived 到另一个方法(Send)
  2. Send 等待 webSocket_MessageReceived 处理程序叫。您可以使用 AutoResetEvent为此(它应该在适用于 Android 的 Xamarin 库中可用)。

请注意,_messageReceivedEvent.WaitOne 会使您的 Send 方法阻塞,因此如果您从 UI 事件处理程序调用此方法,您的 UI 将无响应,直到 _messageReceivedEvent。 Set 被调用。考虑重新设计此类,使其使用异步方法(它可以公开 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();
}

...
}

关于c# - WebSocket4Net - 在 websocket 上收到 'return' 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29836192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com