WebSocket.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Engine\WebSocket;
  12. use Hyperf\Engine\Contract\WebSocket\WebSocketInterface;
  13. use Swoole\Http\Request;
  14. use Swoole\Http\Response;
  15. use Swoole\WebSocket\CloseFrame;
  16. class WebSocket implements WebSocketInterface
  17. {
  18. /**
  19. * @var Response
  20. */
  21. protected $connection;
  22. /**
  23. * @var array<string, callable>
  24. */
  25. protected $events = [];
  26. public function __construct(Response $connection, Request $request)
  27. {
  28. $this->connection = $connection;
  29. $this->connection->upgrade();
  30. }
  31. public function on(string $event, callable $callback): void
  32. {
  33. $this->events[$event] = $callback;
  34. }
  35. public function start(): void
  36. {
  37. while (true) {
  38. $frame = $this->connection->recv();
  39. if ($frame === false || $frame instanceof CloseFrame || $frame === '') {
  40. $callback = $this->events[static::ON_CLOSE];
  41. $callback($this->connection, $this->connection->fd);
  42. break;
  43. }
  44. $callback = $this->events[static::ON_MESSAGE];
  45. $callback($this->connection, $frame);
  46. }
  47. $this->connection = null;
  48. $this->events = [];
  49. }
  50. }