123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
- use Ratchet\ConnectionInterface;
- use Ratchet\MessageComponentInterface;
- class WebSocketHandler implements MessageComponentInterface {
- protected $clients;
- protected $handler;
- public function __construct(Handler $handler) {
- $this->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;
- }
- }
- }
- }
|