WebSocketServer.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. foreach ($this->server->clients as $client) {
  37. $client->send('1');
  38. }
  39. }
  40. public function onMessage(ConnectionInterface $from, $msg)
  41. {
  42. echo "Message from {$from->resourceId}: $msg\n";
  43. foreach ($this->server->clients as $client) {
  44. if ($from !== $client) {
  45. $client->send($msg);
  46. }
  47. }
  48. }
  49. public function onClose(ConnectionInterface $conn)
  50. {
  51. $this->server->clients->detach($conn);
  52. echo "Connection {$conn->resourceId} has disconnected\n";
  53. }
  54. public function onError(ConnectionInterface $conn, \Exception $e)
  55. {
  56. echo "Error: {$e->getMessage()}\n";
  57. $conn->close();
  58. }
  59. }
  60. )
  61. ),
  62. 6002
  63. );
  64. // 启动WebSocket服务器
  65. $this->serverInstance->run();
  66. }
  67. // 将WebSocket服务器的实例暴露给外部
  68. public function pushMessageToClients($message)
  69. {
  70. if ($this->serverInstance) {
  71. // 向所有连接的客户端发送消息
  72. foreach ($this->clients as $client) {
  73. $client->send($message);
  74. }
  75. }
  76. }
  77. }