【问题标题】:Await signalr message in client在客户端等待信号器消息
【发布时间】:2017-12-18 16:38:08
【问题描述】:

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

理论;

  1. Client1message1 发送到 Server 并“等待”响应。
  2. Server 处理一些逻辑
  3. Servermessage2 发送到 Client1Client1 执行等待代码。

调用服务器:

$.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 中无法实现,是否还有其他可以使用的套接字库?

【问题讨论】:

    标签: websocket async-await signalr es6-promise


    【解决方案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);
        }
    

    Update info 将使用 message2 调用客户端,在这种情况下,它是一个要显示给客户端的表。当它完成时,它将通过 JoinGroup 从其等待状态返回,该状态将返回并提醒新用户已加入组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-09
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2020-09-28
      • 1970-01-01
      相关资源
      最近更新 更多