WebSocketHandler.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. use Ratchet\ConnectionInterface;
  3. use Ratchet\MessageComponentInterface;
  4. class WebSocketHandler implements MessageComponentInterface {
  5. protected $clients;
  6. protected $handler;
  7. public function __construct(Handler $handler) {
  8. $this->clients = new \SplObjectStorage;
  9. $this->handler = $handler;
  10. }
  11. public function onOpen(ConnectionInterface $conn) {
  12. $this->clients->attach($conn);
  13. echo "New connection: user {$conn->resourceId}\n";
  14. }
  15. public function onMessage(ConnectionInterface $from, $msg) {
  16. echo "Message from user {$from->resourceId}: $msg\n";
  17. try {
  18. $this->handler->handle(json_decode($msg), $from, $this);
  19. } catch (HandlerException $ex) {
  20. echo "Error in message from user {$from->resourceId}: {$ex->getMessage()}\n";
  21. }
  22. }
  23. public function onClose(ConnectionInterface $conn) {
  24. $this->clients->detach($conn);
  25. echo "User {$conn->resourceId} disconnected\n";
  26. }
  27. public function onError(ConnectionInterface $conn, \Exception $e) {
  28. echo "An error has occurred: {$e->getMessage()}\n";
  29. $conn->close();
  30. }
  31. public function countClients() {
  32. return count($this->clients);
  33. }
  34. public function forEachClients(callable $function) {
  35. foreach ($this->clients as $client) {
  36. $function($client);
  37. }
  38. }
  39. public function forOneClient(int $id, callable $function) {
  40. foreach ($this->clients as $client) {
  41. if ($client->resourceId == $id) {
  42. $function($client);
  43. break;
  44. }
  45. }
  46. }
  47. }