Working with Groups in SignalR 1.x
by Patrick Fletcher, Tom FitzMacken
This topic describes how to add users to groups and persist group membership information.
Overview
Groups in SignalR provide a method for broadcasting messages to specified subsets of connected clients. A group can have any number of clients, and a client can be a member of any number of groups. You don’t have to explicitly create groups. In effect, a group is automatically created the first time you specify its name in a call to Groups.Add, and it is deleted when you remove the last connection from membership in it. For an introduction to using groups, see How to manage group membership from the Hub class in the Hubs API - Server Guide.
There is no API for getting a group membership list or a list of groups. SignalR sends messages to clients and groups based on a pub/sub model, and the server does not maintain lists of groups or group memberships. This helps maximize scalability, because whenever you add a node to a web farm, any state that SignalR maintains has to be propagated to the new node.
When you add a user to a group using the Groups.Add
method, the user receives messages directed to that group for the duration of the current connection, but the user’s membership in that group is not persisted beyond the current connection. If you want to permanently retain information about groups and group membership, you must store that data in a repository such as a database or Azure table storage. Then, each time a user connects to your application, you retrieve from the repository which groups the user belongs to, and manually add that user to those groups.
When reconnecting after a temporary disruption, the user automatically re-joins the previously-assigned groups. Automatically rejoining a group only applies when reconnecting, not when establishing a new connection. A digitally-signed token is passed from the client that contains the list of previously-assigned groups. If you want to verify whether the user belongs to the requested groups, you can override the default behavior.
This topic includes the following sections:
- Adding and removing users
- Calling members of a group
- Storing group membership in a database
- Storing group membership in Azure table storage
- Verifying group membership when reconnecting
Adding and removing users
To add or remove users from a group, you call the Add or Remove methods, and pass in the user’s connection id and group’s name as parameters. You do not need to manually remove a user from a group when the connection ends.
The following example shows the Groups.Add
and Groups.Remove
methods used in Hub methods.
[!code-csharpMain]
1: public class ContosoChatHub : Hub
2: {
3: public Task JoinRoom(string roomName)
4: {
5: return Groups.Add(Context.ConnectionId, roomName);
6: }
7:
8: public Task LeaveRoom(string roomName)
9: {
10: return Groups.Remove(Context.ConnectionId, roomName);
11: }
12: }
The Groups.Add
and Groups.Remove
methods execute asynchronously.
If you want to add a client to a group and immediately send a message to the client by using the group, you have to make sure that the Groups.Add method finishes first. The following code examples show how to do that, one by using code that works in .NET 4.5, and one by using code that works in .NET 4.
Asynchronous .NET 4.5 Example
[!code-csharpMain]
1: public async Task JoinRoom(string roomName)
2: {
3: await Groups.Add(Context.ConnectionId, roomName);
4: Clients.Group(roomName).addChatMessage(Context.User.Identity.Name + " joined.");
5: }
Asynchronous .NET 4 Example
[!code-csharpMain]
1: public void JoinRoom(string roomName)
2: {
3: (Groups.Add(Context.ConnectionId, roomName) as Task).ContinueWith(antecedent =>
4: Clients.Group(roomName).addChatMessage(Context.User.Identity.Name + " joined."));
5: }
In general, you should not include await
when calling the Groups.Remove
method because the connection id that you are trying to remove might no longer be available. In that case, TaskCanceledException
is thrown after the request times out. If your application must ensure that the user has been removed from the group before sending a message to the group, you can add await
before Groups.Remove, and then catch the TaskCanceledException
exception that might be thrown.
Calling members of a group
You can send messages to all of the members of a group or only specified members of the group, as shown in the following examples.
All connected clients in a specified group.
[!code-cssMain]1: Clients.Group(groupName).addChatMessage(name, message);
All connected clients in a specified group except the specified clients, identified by connection ID.
[!code-csharpMain]1: Clients.Group(groupName, connectionId1, connectionId2).addChatMessage(name, message);
All connected clients in a specified group except the calling client.
[!code-cssMain]
1: Clients.OthersInGroup(groupName).addChatMessage(name, message);
Storing group membership in a database
The following examples show how to retain group and user information in a database. You can use any data access technology; however, the example below shows how to define models using Entity Framework. These entity models correspond to database tables and fields. Your data structure could vary considerably depending on the requirements of your application. This example includes a class named ConversationRoom
which would be unique to an application that enables users to join conversations about different subjects, such as sports or gardening. This example also includes a class for the connections. The connection class is not absolutely required for tracking group membership but is frequently part of robust solution to tracking users.
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.ComponentModel.DataAnnotations;
4: using System.Data.Entity;
5:
6: namespace GroupsExample
7: {
8: public class UserContext : DbContext
9: {
10: public DbSet<User> Users { get; set; }
11: public DbSet<Connection> Connections { get; set; }
12: public DbSet<ConversationRoom> Rooms { get; set; }
13: }
14:
15: public class User
16: {
17: [Key]
18: public string UserName { get; set; }
19: public ICollection<Connection> Connections { get; set; }
20: public virtual ICollection<ConversationRoom> Rooms { get; set; }
21: }
22:
23: public class Connection
24: {
25: public string ConnectionID { get; set; }
26: public string UserAgent { get; set; }
27: public bool Connected { get; set; }
28: }
29:
30: public class ConversationRoom
31: {
32: [Key]
33: public string RoomName { get; set; }
34: public virtual ICollection<User> Users { get; set; }
35: }
36: }
Then, in the hub, you can retrieve the group and user information from the database and manually add the user to the appropriate groups. The example does not include code for tracking the user connections. In this example, the await
keyword is not applied before Groups.Add
because a message is not immediately sent to members of the group. If you want to send a message to all members of the group immediately after adding the new member, you would want to apply the await
keyword to make sure the asynchronous operation has completed.
[!code-csharpMain]
1: using Microsoft.AspNet.SignalR;
2: using System;
3: using System.Collections.Generic;
4: using System.Data.Entity;
5: using System.Linq;
6: using System.Threading.Tasks;
7:
8: namespace GroupsExample
9: {
10: [Authorize]
11: public class ChatHub : Hub
12: {
13: public override Task OnConnected()
14: {
15: using (var db = new UserContext())
16: {
17: // Retrieve user.
18: var user = db.Users
19: .Include(u => u.Rooms)
20: .SingleOrDefault(u => u.UserName == Context.User.Identity.Name);
21:
22: // If user does not exist in database, must add.
23: if (user == null)
24: {
25: user = new User()
26: {
27: UserName = Context.User.Identity.Name
28: };
29: db.Users.Add(user);
30: db.SaveChanges();
31: }
32: else
33: {
34: // Add to each assigned group.
35: foreach (var item in user.Rooms)
36: {
37: Groups.Add(Context.ConnectionId, item.RoomName);
38: }
39: }
40: }
41: return base.OnConnected();
42: }
43:
44: public void AddToRoom(string roomName)
45: {
46: using (var db = new UserContext())
47: {
48: // Retrieve room.
49: var room = db.Rooms.Find(roomName);
50:
51: if (room != null)
52: {
53: var user = new User() { UserName = Context.User.Identity.Name};
54: db.Users.Attach(user);
55:
56: room.Users.Add(user);
57: db.SaveChanges();
58: Groups.Add(Context.ConnectionId, roomName);
59: }
60: }
61: }
62:
63: public void RemoveFromRoom(string roomName)
64: {
65: using (var db = new UserContext())
66: {
67: // Retrieve room.
68: var room = db.Rooms.Find(roomName);
69: if (room != null)
70: {
71: var user = new User() { UserName = Context.User.Identity.Name };
72: db.Users.Attach(user);
73:
74: room.Users.Remove(user);
75: db.SaveChanges();
76:
77: Groups.Remove(Context.ConnectionId, roomName);
78: }
79: }
80: }
81: }
82: }
Storing group membership in Azure table storage
Using Azure table storage to store group and user information is similar to using a database. The following example shows a table entity that stores the user name and group name.
[!code-csharpMain]
1: using Microsoft.WindowsAzure.Storage.Table;
2: using System;
3:
4: namespace GroupsExample
5: {
6: public class UserGroupEntity : TableEntity
7: {
8: public UserGroupEntity() { }
9:
10: public UserGroupEntity(string userName, string groupName)
11: {
12: this.PartitionKey = userName;
13: this.RowKey = groupName;
14: }
15: }
16: }
In the hub, you retrieve the assigned groups when the user connects.
[!code-csharpMain]
1: using Microsoft.AspNet.SignalR;
2: using System;
3: using System.Collections.Generic;
4: using System.Threading.Tasks;
5: using Microsoft.WindowsAzure.Storage.Table;
6: using Microsoft.WindowsAzure.Storage;
7: using Microsoft.WindowsAzure;
8:
9: namespace GroupsExample
10: {
11: [Authorize]
12: public class ChatHub : Hub
13: {
14: public override Task OnConnected()
15: {
16: string userName = Context.User.Identity.Name;
17:
18: var table = GetRoomTable();
19: table.CreateIfNotExists();
20: var query = new TableQuery<UserGroupEntity>()
21: .Where(TableQuery.GenerateFilterCondition(
22: "PartitionKey", QueryComparisons.Equal, userName));
23:
24: foreach (var entity in table.ExecuteQuery(query))
25: {
26: Groups.Add(Context.ConnectionId, entity.RowKey);
27: }
28:
29: return base.OnConnected();
30: }
31:
32: public Task AddToRoom(string roomName)
33: {
34: string userName = Context.User.Identity.Name;
35:
36: var table = GetRoomTable();
37:
38: var insertOperation = TableOperation.InsertOrReplace(
39: new UserGroupEntity(userName, roomName));
40: table.Execute(insertOperation);
41:
42: return Groups.Add(Context.ConnectionId, roomName);
43: }
44:
45: public Task RemoveFromRoom(string roomName)
46: {
47: string userName = Context.User.Identity.Name;
48:
49: var table = GetRoomTable();
50:
51: var retrieveOperation = TableOperation.Retrieve<UserGroupEntity>(
52: userName, roomName);
53: var retrievedResult = table.Execute(retrieveOperation);
54:
55: var deleteEntity = (UserGroupEntity)retrievedResult.Result;
56:
57: if (deleteEntity != null)
58: {
59: var deleteOperation = TableOperation.Delete(deleteEntity);
60: table.Execute(deleteOperation);
61: }
62:
63: return Groups.Remove(Context.ConnectionId, roomName);
64: }
65:
66: private CloudTable GetRoomTable()
67: {
68: var storageAccount =
69: CloudStorageAccount.Parse(
70: CloudConfigurationManager.GetSetting("StorageConnectionString"));
71: var tableClient = storageAccount.CreateCloudTableClient();
72: return tableClient.GetTableReference("room");
73: }
74: }
75: }
Verifying group membership when reconnecting
By default, SignalR automatically re-assigns a user to the appropriate groups when reconnecting from a temporary disruption, such as when a connection is dropped and re-established before the connection times out. The user’s group information is passed in a token when reconnecting, and that token is verified on the server. For information about the verification process for rejoining users to groups, see Rejoining groups when reconnecting.
In general, you should use the default behavior of automatically rejoining groups on reconnect. SignalR groups are not intended as a security mechanism for restricting access to sensitive data. However, if your application must double-check a user’s group membership when reconnecting, you can override the default behavior. Changing the default behavior can add a burden to your database because a user’s group membership must be retrieved for each reconnection rather than just when the user connects.
If you must verify group membership on reconnect, create a new hub pipeline module that returns a list of assigned groups, as shown below.
[!code-csharpMain]
1: using Microsoft.AspNet.SignalR;
2: using Microsoft.AspNet.SignalR.Hubs;
3: using System;
4: using System.Collections.Generic;
5: using System.Data.Entity;
6: using System.Linq;
7:
8: namespace GroupsExample
9: {
10: public class RejoingGroupPipelineModule : HubPipelineModule
11: {
12: public override Func<HubDescriptor, IRequest, IList<string>, IList<string>>
13: BuildRejoiningGroups(Func<HubDescriptor, IRequest, IList<string>, IList<string>>
14: rejoiningGroups)
15: {
16: rejoiningGroups = (hb, r, l) =>
17: {
18: List<string> assignedRooms = new List<string>();
19: using (var db = new UserContext())
20: {
21: var user = db.Users.Include(u => u.Rooms)
22: .Single(u => u.UserName == r.User.Identity.Name);
23: foreach (var item in user.Rooms)
24: {
25: assignedRooms.Add(item.RoomName);
26: }
27: }
28: return assignedRooms;
29: };
30:
31: return rejoiningGroups;
32: }
33: }
34: }
Then, add that module to the hub pipeline, as highlighted below.
[!code-csharpMain]
1: public class Global : HttpApplication
2: {
3: void Application_Start(object sender, EventArgs e)
4: {
5: // Code that runs on application startup
6: BundleConfig.RegisterBundles(BundleTable.Bundles);
7: AuthConfig.RegisterOpenAuth();
8: RouteConfig.RegisterRoutes(RouteTable.Routes);
9: RouteTable.Routes.MapHubs();
10: GlobalHost.HubPipeline.AddModule(new RejoingGroupPipelineModule());
11: }
12: }
|