socket.php 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. /**
  3. * WebSocket 服务端启动文件 (WSS 加密版)
  4. *
  5. * 使用方法:
  6. * php socket.php start # 调试模式启动(前台运行)
  7. * php socket.php start -d # 守护进程模式启动(后台运行)
  8. * php socket.php stop # 停止服务
  9. * php socket.php restart # 重启服务
  10. * php socket.php status # 查看运行状态
  11. *
  12. * 客户端连接地址:
  13. * wss://api.myjie.cn:2345?type=user&token=xxx&form_type=3&to_uid=对方UID
  14. */
  15. require __DIR__ . '/vendor/autoload.php';
  16. use Workerman\Worker;
  17. use Workerman\Connection\TcpConnection;
  18. // 日志目录
  19. define('LOG_PATH', __DIR__ . '/runtime/logs/workerman/');
  20. if (!is_dir(LOG_PATH)) {
  21. mkdir(LOG_PATH, 0755, true);
  22. }
  23. // ========== SSL 证书配置(WSS 必须) ==========
  24. // 宝塔证书默认文件名:fullchain.pem(证书)、privkey.pem(私钥)
  25. $ssl_cert_path = __DIR__ . '/config/ssl/fullchain.pem'; // 证书文件
  26. $ssl_key_path = __DIR__ . '/config/ssl/privkey.pem'; // 私钥文件
  27. $context = [];
  28. if (file_exists($ssl_cert_path) && file_exists($ssl_key_path)) {
  29. $context = [
  30. 'ssl' => [
  31. 'local_cert' => $ssl_cert_path,
  32. 'local_pk' => $ssl_key_path,
  33. 'verify_peer' => false,
  34. ]
  35. ];
  36. }
  37. // ==============================================
  38. // 创建 WebSocket 服务(带 SSL 上下文)
  39. $ws_worker = new Worker('websocket://0.0.0.0:2345', $context);
  40. // 启用 SSL 传输层(使 websocket:// 升级为 wss://)
  41. if (!empty($context)) {
  42. $ws_worker->transport = 'ssl';
  43. }
  44. // 设置进程名称
  45. $ws_worker->name = 'ChatWebSocket';
  46. // 设置进程数
  47. $ws_worker->count = 4;
  48. // 设置心跳(60秒无响应则断开)
  49. $ws_worker->pingInterval = 60;
  50. $ws_worker->pingNotResponseLimit = 1;
  51. // 当进程启动时
  52. $ws_worker->onWorkerStart = function($worker) {
  53. echo "[Worker #{$worker->id}] started\n";
  54. // 初始化 ChatService
  55. $chatService = new \app\services\workerman\chat\ChatService($worker);
  56. $worker->chatService = $chatService;
  57. };
  58. // 当客户端连接时
  59. $ws_worker->onConnect = function(TcpConnection $connection) {
  60. $addr = $connection->getRemoteAddress();
  61. echo "[Connect] {$addr}\n";
  62. };
  63. // WebSocket 握手回调 - 解析 URL 查询参数(包括 to_uid)
  64. $ws_worker->onWebSocketConnect = function(TcpConnection $connection) {
  65. // 从 URL 查询字符串解析参数
  66. // 例如: wss://api.myjie.cn:2345?type=user&token=xxx&form_type=3&to_uid=456
  67. $query = $_GET ?? [];
  68. $connection->type = $query['type'] ?? 'user';
  69. $connection->token = $query['token'] ?? '';
  70. $connection->form_type = $query['form_type'] ?? 3;
  71. $connection->to_uid = isset($query['to_uid']) ? intval($query['to_uid']) : 0; // 聊天对象UID
  72. echo "[WebSocket Connect] type={$connection->type}, to_uid={$connection->to_uid}\n";
  73. };
  74. // 当收到客户端消息时
  75. $ws_worker->onMessage = function(TcpConnection $connection, $data) use (&$chatService) {
  76. $chatService->onMessage($connection, $data);
  77. };
  78. // 当客户端断开连接时
  79. $ws_worker->onClose = function(TcpConnection $connection) use (&$chatService) {
  80. $chatService->onClose($connection);
  81. };
  82. // 当连接出错时
  83. $ws_worker->onError = function(TcpConnection $connection, $code, $msg) {
  84. echo "[Error] {$code}: {$msg}\n";
  85. };
  86. // 输出启动信息
  87. $ssl_ok = !empty($context);
  88. echo "\n";
  89. echo "========================================\n";
  90. echo " Chat WebSocket Server (WSS)\n";
  91. echo " Address: " . ($ssl_ok ? "wss" : "ws") . "://0.0.0.0:2345\n";
  92. if (!$ssl_ok) {
  93. echo " [警告] SSL 证书未配置,运行在 ws 模式\n";
  94. echo " 请将证书放到 config/ssl/cert.pem 和 config/ssl/key.pem\n";
  95. }
  96. echo " PID: " . getmypid() . "\n";
  97. echo "========================================\n\n";
  98. // 运行
  99. Worker::runAll();