SignalR: How does server correctly subscribe to a

2019-07-22 03:05发布

问题:

I have look at the several places, but still can not find clear instructions on how groups should be used. I am using a groups for filtering (delivering the message just to subset of clients).

I would like to join a client to the group on the server side in OnConnected event. Client does not need to know to which groups it belongs.

Questions:

  1. Should I also override the OnReconnected event?

  2. Should I return the Task returned from GroupManager.Add as the result of OnConnected event? If I would like to join multiple groups, I probably need to create a combined task. Right?

3- Why does the server (see GroupManager.Add implementation) sends the AddToGroup command the client? Is there a way to work around this? Maybe by using Client.AllExcept(...) and manually handling group membership on the server (yuck!)?

I am using the latest version of SignalR (1.0.0.1)

回答1:

  1. You do not need to override OnReconnected. When a client reconnects it will rejoin all groups it was previously in.
  2. You don't have to, but if you try sending to that group within the OnConnected (if you choose to not return the group addition task) you will need to wait until the task completes.
  3. You do not want to work around this, one of the reasons its necessary is because of #2 (the client needs to know what groups it is in). If you want to authenticate groups for reconnect you can always create a hub pipeline module and override the BuildRejoiningGroups function to perform your own verification.

Response to Comments

Comment 1: Yes
Comment 2: You must return a task otherwise nothing will complete (this is by design). If you do not know what to return you can always return base.OnConnected().

When you call GroupManager.Add it returns a task that represents when the connection is in the desired group. Once joining the group the client then gets notified that its now in a new group via a token. The token will then allow the client to rejoin the group if it has to reconnect due to loss of connectivity.