WebSocketServer.php 3.0 KB

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