4

I'm confused about the closed event in SignalR. Apparently, there was some debate about what to call it e.g. onClosed(), closed(), etc.

In my SignalR listener on the client side, I'm trying to implement this event but I keep getting an error that says it's not a function. I tried onClosed() and closed(). Same error. How do I detect the closed event on the client side?

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
   })

}

What am I doing wrong?

Here's how I start my connection:

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();
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Sam
  • 26,817
  • 58
  • 206
  • 383

1 Answers1

5

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();

};

Reference ASP.NET Core SignalR JavaScript client

Reference SignalR JavaScript API - HubConnection class

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 1
    Yes, this is the correct solution and it's working now. Correct event handler is `onclose()` NOT `onClosed()` or `onClose()`. Changed the order and now registering the handlers first. Thank you very much for your help! – Sam Jul 23 '18 at 20:56
  • @Sam I included a link to the HubConnection API so you can see the available members. – Nkosi Jul 23 '18 at 21:04