diff --git a/doc/ConnectionGroups.md b/doc/ConnectionGroups.md new file mode 100644 index 0000000..f9010d5 --- /dev/null +++ b/doc/ConnectionGroups.md @@ -0,0 +1,16 @@ +# 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, call `setGroup(null)`. diff --git a/src/WebSocketConnection.php b/src/WebSocketConnection.php index 075b5c7..e5586dd 100644 --- a/src/WebSocketConnection.php +++ b/src/WebSocketConnection.php @@ -214,25 +214,28 @@ class WebSocketConnection implements WebSocketInterface } public function write($data) - { - // Header; final, text frame, unmasked - $frame = chr(0x81) . chr(strlen($data)) . $data; - - $this->outStream->write($frame); + { + return $this->send(self::OP_FRAME_TEXT, $data); } - public function send(int $opcode, bool $final, string $data) + /** + * + */ + public function send(int $opcode, string $data, bool $final = true) { $frame = chr(($final?0x80:0x00) | ($opcode & 0xF)); $len = strlen($data); if ($len > 126) { $frame .= chr(0x7E) . chr(($len >> 8) & 0xFF) . chr($len & 0xFF); + } else { + $frame .= chr($len); } $frame .= $data; $this->outStream->write($frame); + return true; } public function close() @@ -245,5 +248,25 @@ class WebSocketConnection implements WebSocketInterface { } - + + // private function hexdump($data): void + // { + // printf("%4d .\n", strlen($data)); + // $rows = str_split($data, 16); + // $offs = 0; + // foreach ($rows as $row) { + // $h = []; $a = []; + // for ($n = 0; $n < 16; $n++) { + // if ($n < strlen($row)) { + // $h[] = sprintf("%02x%s", ord($row[$n]), ($n==7)?" ":" "); + // $a[] = sprintf("%s%s", (ctype_print($row[$n])?$row[$n]:"."), ($n==7)?" ":""); + // } else { + // $h[] = (($n==7)?" ":" "); + // $a[] = (($n==7)?" ":" "); + // } + // } + // printf("%04x | %s | %s\n", 16 * $offs++, join("", $h), join("", $a)); + // } + // } + } \ No newline at end of file