Search code examples
signalr.clientasp.net-core-signalr

SignalR Core call function when connection is established


When my client successfully connects to the hub, I want the client to immediately join a group. I have a method in my hub to do that, I just need an event handler for when the connection is established, just like

connection.start().done(
    function () {
        connection.invoke('JoinGroup', 'GroupName');
    });

in SignalR for plain ASP.Net.

Can I do that or do I have to set a timer to do it after x seconds after the start(); call was made?

Edit:

I found out I can do

connection.start(
    function (){
            connection.invoke('JoinGroup', 'GroupName');
    }
);

but it tells me that it Cannot send data if the connection is not in the 'Connected' State.

what do?


Solution

  • SignalR is notoriously difficult due to version mismatches etc.

    Please see the following article: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.1&tabs=visual-studio

    In it, there's a section that specifies how to start (and wait for connection to be established):

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

    The javascript client uses promises that have to be resolved/rejected before you can use it. The other option is to wrap inside async method and await the call (not sure if this will work correctly). Such as:

    await connection.start();
    //connection should be started now. beware of exceptions though