WebSocketServer.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Console\Commands;
  3. use Ratchet\MessageComponentInterface;
  4. use Ratchet\ConnectionInterface;
  5. use Ratchet\Server\IoServer;
  6. use Ratchet\Http\HttpServer;
  7. use Ratchet\WebSocket\WsServer;
  8. use Illuminate\Console\Command;
  9. class WebSocketServer extends Command
  10. {
  11. protected $signature = 'websocket:start';
  12. public $clients;
  13. protected $serverInstance;
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. $this->clients = new \SplObjectStorage;
  18. }
  19. public function handle()
  20. {
  21. $this->info('WebSocket server starting on ws://121.37.173.82:6002');
  22. // 创建WebSocket服务器实例
  23. $this->serverInstance = IoServer::factory(
  24. new HttpServer(
  25. new WsServer(
  26. new class($this) implements MessageComponentInterface {
  27. private $server;
  28. public function __construct($server)
  29. {
  30. $this->server = $server;
  31. }
  32. public function onOpen(ConnectionInterface $conn)
  33. {
  34. $this->server->clients->attach($conn);
  35. echo "New connection! ({$conn->resourceId})\n";
  36. }
  37. public function onMessage(ConnectionInterface $from, $msg)
  38. {
  39. echo "Message from {$from->resourceId}: $msg\n";
  40. foreach ($this->server->clients as $client) {
  41. if ($from !== $client) {
  42. $client->send($msg);
  43. }
  44. }
  45. }
  46. public function onClose(ConnectionInterface $conn)
  47. {
  48. $this->server->clients->detach($conn);
  49. echo "Connection {$conn->resourceId} has disconnected\n";
  50. }
  51. public function onError(ConnectionInterface $conn, \Exception $e)
  52. {
  53. echo "Error: {$e->getMessage()}\n";
  54. $conn->close();
  55. }
  56. }
  57. )
  58. ),
  59. 6002
  60. );
  61. // 启动WebSocket服务器
  62. $this->serverInstance->run();
  63. }
  64. // 将WebSocket服务器的实例暴露给外部
  65. public function pushMessageToClients($message)
  66. {
  67. if ($this->serverInstance) {
  68. // 向所有连接的客户端发送消息
  69. foreach ($this->clients as $client) {
  70. $client->send($message);
  71. }
  72. }
  73. }
  74. }