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.
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.
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).
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.
Find below a Server/Client Demo that shows the main features of sgcWebSockets Groups.