等待客户端

时间:2017-12-18 16:38:09

标签: websocket async-await signalr es6-promise

SignalR客户端是否有可能向服务器发送消息,然后等待来自服务器的单独消息(而不是返回值)?

理论;

  1. Client1 message1 发送给Server和"等待"为了回应。
  2. Server处理一些逻辑
  3. Server message2 发送给Client1Client1执行等待代码。
  4. 致电服务器:

    $.connection.myhub.server.myRequest(id).done(()==>{
      // myRequest is done;
      // the server has received the request but hasn't processed it yet.
      // I want put some *async* code here to do something when the server has triggered $.connection.myhub.client.myResponse(id, someParam);
    });
    

    回拨给客户:

    $.connection.myhub.client.myResponse(originalId, somePassedBackValue);
    

    我可以使用Async / Await,还是以某种方式将其包装在Promise中?

    如果在SignalR中没有这个功能,是否还有其他套接字库可以替代使用?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

想象一下,您有一个加入组的客户端,更新表,然后通知客户端它已加入。

<强>客户端

msgHub.server.joinGroup(id).done(function () {
    console.log("Joined Group");
    serverCallFinished = true;
})

msgHub.client.displayTable = function (table) {
    display(table);
}

<强>集线器

public async Task JoinGroup(string practiceId)
{
    try
    {
        await Groups.Add(Context.ConnectionId, practiceId);
        //Add new table
        var table = new Table(practiceId)
        await UpdateTable("SomeGroup", table);
    }
    catch (Exception e)
    {
        throw;
    }
}

public async Task UpdateInfo(string groupName, string table)
    {
        //await some logic
        Clients.Group(groupName).updateTable(table);
    }

更新信息将使用message2调用客户端,在这种情况下是一个要显示给客户端的表。当它完成时,它将从等待状态返回JoinGroup,它将返回并警告新用户已加入一个组。