Trevor Daniel
Trevor Daniel

Reputation: 3954

SignalR Get Connection Id

I am making my first attempt at using SignalR to give feedback of the progress of a long running process to a user

I have found some .Net Core examples but the closest appears to be using an older version of SignalR.

I am struggling to get the "ConnectionId". I have read numerous SO questions and answers and still cannot seem to get the correct value.

This is the code I have from the demo project I found:

// Helper functions added for test purposes
function openConnection() {
    progressConnection = new signalR.HubConnectionBuilder().withUrl("/progressDemo").build();
    debugger;
    progressConnection
        .start()
        .then(() => {
            progressConnectionId = progressConnection.connection.connectionId;
            $("#connId").html(progressConnectionId);
            $("#startButton").removeAttr("disabled");
            $("#dropConnectionButton").removeAttr("disabled");
            $("#openConnectionButton").attr("disabled", "disabled");
            $("#msg").html("Connection established");
            console.log("Connection Id: " + progressConnectionId);
        })
        .catch(() => {
            $("#msg").html("Error while establishing connection");
        });
}

The error is that the "connectionId" is undefined on the line:

progressConnectionId = progressConnection.connection.connectionId;

Any help would be greatly appreciated!

Upvotes: 2

Views: 6315

Answers (2)

Khalil Kothia
Khalil Kothia

Reputation: 41

I guess below would be more effecient as it won't send the connection Id to all connected id...

public override Task OnConnectedAsync()
{
    //Count++;
    Interlocked.Increment(ref Count);

    base.OnConnectedAsync();
    Clients.All.SendAsync("updateCount", Count);
    Clients.Client(Context.ConnectionId).SendAsync("connected", Context.ConnectionId);
    return Task.CompletedTask;
}

Upvotes: 2

Trevor Daniel
Trevor Daniel

Reputation: 3954

Ok... this is pretty obvious now I have solved it :)

My hub now looks like this:

public override Task OnConnectedAsync()
{
    //Count++;
    Interlocked.Increment(ref Count);

    base.OnConnectedAsync();
    Clients.All.SendAsync("updateCount", Count);
    Clients.All.SendAsync("connected", Context.ConnectionId);
    return Task.CompletedTask;
}

The important line is the one that sends back the connection Id

Clients.All.SendAsync("connected", Context.ConnectionId);

On the client side I then listen for "connected" and set the connectionId variable:

progressConnection.on("connected", (connectionId) => {
    progressConnectionId = connectionId;
    $("#connId").html(progressConnectionId);
    $("#startButton").removeAttr("disabled");
    $("#dropConnectionButton").removeAttr("disabled");
    $("#openConnectionButton").attr("disabled", "disabled");
    $("#msg").html("Connection established");
    console.log("Connection Id: " + progressConnectionId);
});

Upvotes: 3

Related Questions