connection.closed 不是函数 SignalR

connection.closed is not a function SignalR

我对 SignalR 中的已关闭事件感到困惑。显然,关于如何称呼它存在一些争论,例如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();
}

As a best practice, call connection.start after connection.on so your handlers are registered before any messages are received.

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