等待异步方法中的事件

时间:2018-10-16 10:57:35

标签: c#

我正在使用WebsocketSharp库访问ESP32上的Websocket服务器。 当websocket客户端向服务器发送消息时,将调用服务器中的此方法,例如以获取设备信息数据:

void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){    

    if(type == WS_EVT_DATA){
      Log.notice("Websocket data received" CR);     

      if(jsonDecoder.GetMessageType(stringData) == "RequestGetDeviceInfo"){
          auto msg = jsonDecoder.CreateDeviceInfoMessage(
          //Create json with the data, and "MessageType" is "DeviceInfo"
          );          
      //here the request gets an answer
          socket.text(client ->id(),msg);
      }
    }      
}

在客户端上,存在一种模式,要么发送某些内容,要么使用接收到的数据触发一个事件。因此,当使用MessageType“ RequestDeviceInfo”发送json消息时,将触发该事件:

using (var ws = new WebSocket("ws://192.168.178.34/ws"))
{
   var msg = JsonConvert.SerializeObject(new Message()
   {
       MessageType = "RequestDeviceInfo",
   });


   ws.OnMessage += (sender, e) =>
   {
       //e.Data contains the json with MessageType "DeviceInfo"
       string jsonAnswer = e.Data;
   };

}

因此,如果发送了请求,则事件将使用json响应触发100%。 我的问题是:如何将其打包成“ get”方法(最好是超时)?喜欢:

async DeviceInfo GetDeviceInfo()
{
           //Send the request and wait for the event and return the e.Data 
}

谢谢。

0 个答案:

没有答案
相关问题