Lajos Arpad
Lajos Arpad

Reputation: 77012

Is it possible to make a session-specific SIgnalR connection?

Let us suppose that I am implementing a visitor counter with SignalR. A static variable is incremented whenever a new visitor arrives and is decremented whenever a visitor left the building. I wonder whether a connection be session-specific, so I can increment the counter whenever a new session was created and decrement it whenever a session is no longer connected.

This would mean that whenever a user successfully logs in or opens the first tab in a browser when already logged in, the counter should be incremented and whenever the last such tab in a browser is closed, the counter should be decremented. I can do it as follows:

I wonder whether this is possible with SignalR out of the box, so that SignalR would track connections to a sessionid. Is it?

Upvotes: 0

Views: 355

Answers (1)

Sayan Pal
Sayan Pal

Reputation: 4956

Considering you are using Hub classes, you can do this by using server side events and corresponding handlers, such as OnConnected, and OnDisconnected.

public class ContosoChatHub : Hub
{
    public override Task OnConnected()
    {
        //this is called after connection is started.
        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        //called when the connection is disconnected.
        return base.OnDisconnected();
    }
}

For more information, please check How to handle connection lifetime events in the Hub class.

Update: Whenever a new connection will be made, OnConnected will be called automatically by SignalR framework. There you can increase your static variable and what not. And in OnDisconnected, you can decrease the variable that is called whenever a connection is destroyed/stopped.

Other than this, you can also persist User, Group, and Connection information, in external memory like SQL Server, and track it explicitly.

Upvotes: 2

Related Questions