【问题标题】:connection.closed is not a function SignalRconnection.close 不是函数 SignalR
【发布时间】:2018-07-24 05:08:06
【问题描述】:

我对@9​​87654321@ 中的关闭事件感到困惑。显然,有一些关于如何称呼它的争论,例如onClosed()closed()

在客户端的SignalR 侦听器中,我正在尝试实现此事件,但我不断收到错误消息,指出它不是函数。我试过onClosed()closed()。同样的错误。如何在客户端检测到关闭的事件?

const signalRListener = () => {

   connection.on('new_message', message => {

      // Handle incoming message.
      // This is working fine.
   })

   connection.closed(e => {

       // Try to restart connection but I never get here to due error I'm receiving
   })

}

我做错了什么?

这是我开始连接的方式:

export const signalRStart = (token) => {

    connection = new signalR.HubConnectionBuilder()
        .withUrl("/chat?access_token=" + token)
        .configureLogging(signalR.LogLevel.Information)
        .build();

    // Set connection time out
    connection.serverTimeoutInMilliseconds = 30000;

    // Start connection
    connection.start();

    // Invoke listener
    signalRListener();
}

【问题讨论】:

    标签: asp.net-core signalr signalr.client asp.net-core-signalr


    【解决方案1】:

    作为最佳实践,在connection.on 之后调用connection.start,以便在收到任何消息之前注册您的处理程序。

    export const signalRStart = (token) => {
    
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/chat?access_token=" + token)
            .configureLogging(signalR.LogLevel.Information)
            .build();
    
        // Set connection time out
        connection.serverTimeoutInMilliseconds = 30000;
    
        //register listeners
    
        //Registers a handler that will be invoked when the hub method with the specified method name is invoked.
        connection.on('new_message', message => {    
            // Handle incoming message.
            // This is working fine.
        });
    
        //Registers a handler that will be invoked when the connection is closed.
        connection.onclose(e => {
            // ...
        });
    
        // Start connection
        connection.start();
    
    };
    

    参考ASP.NET Core SignalR JavaScript client

    参考SignalR JavaScript API - HubConnection class

    【讨论】:

    • 是的,这是正确的解决方案,它现在正在运行。正确的事件处理程序是 onclose() 而不是 onClosed()onClose()。更改了顺序,现在首先注册处理程序。非常感谢您的帮助!
    • @Sam 我包含了 HubConnection API 的链接,以便您查看可用的成员。
    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2014-04-19
    • 2011-12-04
    • 2016-11-21
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多