建立连接时的 SignalR Core 调用函数

len*_*nyy 1 signalr.client asp.net-core-signalr

当我的客户端成功连接到集线器时,我希望客户端立即加入一个组。我的集线器中有一个方法可以做到这一点,我只需要一个连接建立时的事件处理程序,就像

connection.start().done(
    function () {
        connection.invoke('JoinGroup', 'GroupName');
    });
Run Code Online (Sandbox Code Playgroud)

在用于普通 ASP.Net 的 SignalR 中。

我可以这样做还是我必须设置一个计时器才能在start();呼叫发出x 秒后执行此操作?

编辑:

我发现我可以做到

connection.start(
    function (){
            connection.invoke('JoinGroup', 'GroupName');
    }
);
Run Code Online (Sandbox Code Playgroud)

但它告诉我它 Cannot send data if the connection is not in the 'Connected' State.

做什么?

小智 7

由于版本不匹配等原因,SignalR 非常困难。

请参阅以下文章:https : //docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.1&tabs=visual-studio

其中,有一个部分指定了如何启动(并等待建立连接):

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.start().then(() => {
  //try some stuff here :)
})
.catch(function (err) {
  //failed to connect
  return console.error(err.toString());
});
Run Code Online (Sandbox Code Playgroud)

javascript 客户端使用的承诺必须在您可以使用之前解决/拒绝。另一种选择是包装在 async 方法中并等待调用(不确定这是否能正常工作)。如:

await connection.start();
//connection should be started now. beware of exceptions though
Run Code Online (Sandbox Code Playgroud)