SignalR客户端是否有可能向服务器发送消息,然后等待来自服务器的单独消息(而不是返回值)?
理论;
Client1
将 message1 发送给Server
和"等待"为了回应。Server
处理一些逻辑Server
将 message2 发送给Client1
,Client1
执行等待代码。致电服务器:
$.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中没有这个功能,是否还有其他套接字库可以替代使用?
答案 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,它将返回并警告新用户已加入一个组。