Norman Bentley
Norman Bentley

Reputation: 660

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.

Upvotes: 1

Views: 793

Answers (2)

radu-matei
radu-matei

Reputation: 3520

What I do is when the user connects, in the OnConnected method I simply add their ConnectionId to a key in the database that is similar to:

UserId:HubName:ConnectionId

The HubName part I get through reflection: Type.GetType().Name

I use this key to add in the database when the user connects and remove it from the same database when OnDisconnected gets called.

Now, keep in mind that if the server fails at some point, the OnDisconnected method doesn't get called, so you are left in the database with some ConnectionId's that you think belong to a user, but they actually no longer do.

Every time the server starts, I would search the database for ConnnectionId's and verify if they are actually active (most probably not) and delete them.

Hope this helps. Best of luck!

Upvotes: 1

huysentruitw
huysentruitw

Reputation: 28151

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.

Upvotes: 1

Related Questions