WebSocketServer.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. public function __construct()
  14. {
  15. parent::__construct();
  16. $this->clients = new \SplObjectStorage;
  17. }
  18. public function handle()
  19. {
  20. $this->info('WebSocket server starting on ws://121.37.173.82:6002');
  21. $server = IoServer::factory(
  22. new HttpServer(
  23. new WsServer(
  24. new class($this) implements MessageComponentInterface {
  25. private $server;
  26. public function __construct($server)
  27. {
  28. $this->server = $server;
  29. }
  30. public function onOpen(ConnectionInterface $conn)
  31. {
  32. $this->server->clients->attach($conn);
  33. echo "New connection! ({$conn->resourceId})\n";
  34. }
  35. public function onMessage(ConnectionInterface $from, $msg)
  36. {
  37. echo "Message from {$from->resourceId}: $msg\n";
  38. foreach ($this->server->clients as $client) {
  39. if ($from !== $client) {
  40. $client->send($msg);
  41. }
  42. }
  43. }
  44. public function onClose(ConnectionInterface $conn)
  45. {
  46. $this->server->clients->detach($conn);
  47. echo "Connection {$conn->resourceId} has disconnected\n";
  48. }
  49. public function onError(ConnectionInterface $conn, \Exception $e)
  50. {
  51. echo "Error: {$e->getMessage()}\n";
  52. $conn->close();
  53. }
  54. }
  55. )
  56. ),
  57. 6002
  58. );
  59. $server->run();
  60. }
  61. public function pushMessageToClients($message)
  62. {
  63. // 向所有连接的客户端发送消息
  64. foreach ($this->clients as $client) {
  65. $client->send($message);
  66. }
  67. }
  68. }