WebSocket Groups: Channels, Users and more

From sgcWebSockets 2023.2.0 a new feature has been implemented to improve Server Message Broadcasting. Groups is a new feature in sgcWebSockets library, that allows you to organize connections (representing clients, such as browsers) into named groups. This allows you to broadcast messages to all connections in a group instead of sending the message to each connection individually. sgcWebSockets Groups are useful for scenarios where you want to broadcast a message to a specific set of clients, such as a chat room or a multiplayer game.

Adding and removing users

To add or remove users from a group, you call the Add or Remove methods, and pass the Group Name and the TsgcWSConnection class. You do not need to manually remove a user from a group when the connection ends.

The following example shows the Groups.Add method. 

procedure OnConnect(Connection: TsgcWSConnection);
  TsgcWebSocketServer1.Groups.Add('Room1', Connection);

Sending Messages to a Group

Now, this connection is inside the Group called "Room1", if there are more users in this group, you can just Broadcast a message to all member of the group "Room1" using the method Broadcast. 

TsgcWebSocketServer1.Groups.Group['Room1'].Broadcast('Hello Members of Room1'); 

Or you can send a message to all groups that start with "Room" (so if exists Room1, Room2, Room3... these users will receive a message). 

TsgcWebSocketServer1.Groups.Broadcast('Room*', 'Hello Members of Room1'); 

The GroupName paramenter of Broadcast makes use of the function MatchesMask to know if the group must be included in the broadcasted message, so you can use it for advanced configurations. 

Group Events

There are 2 events that can be used to handle the Groups and Clients every time a new client is added to a group or when is removed:

- OnClientAdded: every time a user is added to a group, this is event is called.

- OnClientRemoved: called every time a client is removed from a group (usually when disconnects).

Example, send a message to the group when a member leaves the group.

TsgcWebSocketServer1.Groups.OnClientRemoved := OnClientRemovedEvent;
procedure OnClientRemovedEvent(Sender: TObject; const aGroup: TsgcWSServerGroupItem; 
  const aConnection: TsgcWSConnection);
  aGroup.BroadCast('Client ' + aConnection.Guid + ' has disconnected');

Find below a Server/Client Demo that shows the main features of sgcWebSockets Groups. 

4.2 mb
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

Mapping Groups and Connections
sgcWebSockets 2023.1

Related Posts