clients = new \SplObjectStorage; $this->handler = $handler; } public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); echo "New connection: user {$conn->resourceId}\n"; } public function onMessage(ConnectionInterface $from, $msg) { echo "Message from user {$from->resourceId}: $msg\n"; try { $this->handler->handle(json_decode($msg), $from, $this); } catch (HandlerException $ex) { echo "Error in message from user {$from->resourceId}: {$ex->getMessage()}\n"; } } public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); echo "User {$conn->resourceId} disconnected\n"; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "An error has occurred: {$e->getMessage()}\n"; $conn->close(); } public function countClients() { return count($this->clients); } public function forEachClients(callable $function) { foreach ($this->clients as $client) { $function($client); } } public function forOneClient(int $id, callable $function) { foreach ($this->clients as $client) { if ($client->resourceId == $id) { $function($client); break; } } } }