react-websocket/doc/ConnectionGroups.md

51 lines
2.2 KiB
Markdown
Raw Permalink Normal View History

# ConnectionGroups
Often websocket connections share a context. This could be a room for a chat, an URI for pushing updates, or anything else where one client need to be able to send messages directly or indirectly to other clients. This is the problem that *ConnectionGroups* solve.
A `WebSocketConnection` can, but doesn't have to, be part of a group. The group is set using `WebSocketConnection::setGroup(string $name)` with groups being created and destroyed on the fly. Once part of a group, the other members of the group can be addressed:
```php
$websocket->setGroup("somename");
// Note: use getGroupName() to get the group name
foreach ($websocket->getGroup() as $other) {
$other->write("Hello");
}
```
To remove a group from a connection, pass `null` to `WebSocketConnection::setGroup()`.
2024-02-21 21:43:31 +00:00
The group will emit a `join` event (`ConnectionGroup::EVENT_JOIN`) when another member joins the group, and a `leave` event (`ConnectionGroup::EVENT_LEAVE`) when a member leaves. The events will be sent to the leaving member as well, so consider this in your logic.
## Events
The GroupManager emits events when a group is `created` (`GroupManager::EVENT_CREATED`) or `destroyed` (`GroupManager::EVENT_DESTROYED`). You can use these events to hook the join and leave events.
```php
// Create a GroupManager
$groupManager = new GroupManager();
$groupManager->on('created', function (ConnectionGroup $group) {
// Listen for joins
$group->on('join', function (WebSocketConnection $connection) use ($group) {
// Someone joined the group!
$group->write("Someone joined!");
})
});
// The GroupManager is injected into the WebSocketMiddleware
$middleware = new WebSocketMiddleware($groupManager);
```
2024-02-22 01:01:12 +00:00
## Sending messages
You can use the `ConnectionGoup::writeAll(string $payload)` method to send the payload to all members of the group.
## Disconnecting clients
You can disconnect clients cleanly on shutdown by using the `GroupManager::closeAll(string $reason, int $code)` method. You can also call on `ConnectionGrroup::closeAll` manually do disconnect a whole group.
2024-02-21 21:43:31 +00:00
## Future
* Add a GroupManagerImplementation so custom logic can be provided.
* Make it possible to reject setting a group by GroupManager not returning a group.