Manage multiple browser tabs in signalr

Question

I am developing a chat application like facebook in MVC 4.

I am connecting to hub like following

var chat = $.connection.chatHub;

$.connection.transports.longPolling.supportsKeepAlive = function () {
    return false;
}
$.connection.hub.qs = "UserID=" + $('#hdfLoggedInUserID').val();
$.connection.hub.start().done(function () {
    //...
});
$.connection.hub.disconnected(function () {
    setTimeout(function () {
        $.connection.hub.start();
    }, 5000); // Restart connection after 5 seconds.
});

And my hub class is like following

    public override Task OnConnected()
    {
        var userID = Context.QueryString["UserID"];
        if (userID != null)
        {
            //set user online in database and save connection_id
            RefreshOnlineUsers(uId);
        }
        return base.OnConnected();
    }
    public override Task OnDisconnected(bool stopCalled)
    {
        var userID = Context.QueryString["UserID"];
        if (userID != null)
        {
            //set user offline in database
            RefreshOnlineUsers(uId);
        }
        return base.OnDisconnected(stopCalled);
    }

It's working fine when I am working with only one browser tab.

OnConnected calls when browser tab open and OnDisconnected calls when browser tab closed. So according to this when I open one tab then OnConnected calls and user's status(online) and connection_id update in database.

After that I open my application in new tab of same browser then OnConnected method calls again and user's new connection_id and status(online) update in database.

After that when I close new browser tab then OnDiconnected calls and user's status changes to offline in database. But user is still online in previous browser tab.

Due to this issue this user is offline according to database but it's online.

I am already done lot of R&D about it but can't find any proper solution.

Q : How can I resolve this multiple browser tab issue?

Thanks.


Show source
| jquery   | c#   | asp.net-mvc   | signalr   | sockets   2017-01-02 10:01 1 Answers

Answers to Manage multiple browser tabs in signalr ( 1 )

  1. 2017-01-02 13:01

    Thanks thab.

    You said :

    You are only tracking the user whereas you need to track the connectionId also. When the user has no active connectionIds then they are offline etc

    This is a great idea and I implemented this. This works great. I am tracking connectionId . When the user has no active connectionIds then they will be offline other wise they will be online.

Leave a reply to - Manage multiple browser tabs in signalr

◀ Go back