Search code examples
c#asp.netsignalrsignalr-hub

SignalR: Managing OnDisconnect() with multiple hubs


I have a SignalR application which manages users and connections, User / Room, with a database. I followed the following article (under Permanent, external storage -> Database)

http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections

As someone logs in, I insert their entry into a Room table, and remove it as they leave.

I now have two hubs, "Chat" and "Game".

Lets say for example UserA into both Chat and Game hub. I create 2 entries into both a Chat table and Game table. However, if UserA does a 'non-graceful' close of a single hub (ie. close tab), I am not able to pick which room/hub UserA disconnected from. (OnDisconnect does not allow me to capture these details). This forces me to remove all occurrences of UserA across all tables he is found in on my database

Now how is it possible for me to know which hub UserA exited from so that I may only remove his entry for that particular room. (e.g. UserA is in both Game Room and Chat Room. He closes the Game Room window. Application needs to only remove his entry from Game Room table.)

Any input, suggestions is much appreciated.


Solution

  • In every method that is called in your SignalR Hub you have access to the unique ConnectionId through this.Context.ConnectionId. You should link this id to the user.

    Once in the OnDisconnected handler, use that ConnectionId to know which user has left.

    And according to this article:

    The connection ID is a GUID that is assigned by SignalR (you can't specify the value in your own code). There is one connection ID for each connection, and the same connection ID is used by all Hubs if you have multiple Hubs in your application.