react-websocket/doc/ConnectionGroups.md

1.1 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 (WebSocketConnection::EVENT_JOIN) when another member joins the group, and a leave event (WebSocketConnection::EVENT_LEAVE) when a member leaves. The events will be sent to the leaving member as well, so consider this in your logic.