react-websocket/doc/ConnectionGroups.md

2.2 KiB

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:

$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().

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.

// 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);

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.

Future

  • Add a GroupManagerImplementation so custom logic can be provided.
  • Make it possible to reject setting a group by GroupManager not returning a group.