用webman+AI写了聊天室的代码,服务端一直收不到消息,哪里的问题啊?

落落

问题描述

用webman+AI写了聊天室的代码,服务端一直收不到消息,哪里的问题啊?

<?php
namespace app\process;

use support\Log;
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Timer;

class ChatServer
{
    protected static $connections = [];
    protected static $connectionMap = []; // 新增:IP到连接的映射

    public function onWorkerStart()
    {
        // 创建 WebSocket 服务器
        Log::channel('timer')->info("WebSocket 服务器启动", ['port' => '8788']);
        $ws_worker = new Worker('websocket://0.0.0.0:8788');
        $ws_worker->name='tt';
        //$ws_worker->count = 3;

        // 心跳设置
        define('HEARTBEAT_INTERVAL', 25);

        // 连接建立
        $ws_worker->onConnect = function (TcpConnection $connection) {
            $ip = $connection->getRemoteIp();
            $port = $connection->getRemotePort();
            $connectionId = "$ip:$port";

            // 存储连接
            self::$connections[$connection->id] = $connection;
            self::$connectionMap[$connectionId] = $connection->id;
            $connection->lastMessageTime = time();
            $connection->send(json_encode([
                'type' => 'system',
                'message' => '欢迎加入聊天室!请设置昵称',
                'time' => date('H:i')
            ]));
            Log::channel('timer')->info("system", ['broadcast' => [
                'type' => 'system',
                'message' => '欢迎加入聊天室!请设置昵称',
                'time' => date('H:i')
            ]]);
        };

        // 收到消息
        $ws_worker->onMessage = function (TcpConnection $connection, $data) {
            $connection->send("hello");
            Log::channel('timer')->info("收到消息", ['connection_id' => $connection->id,'raw_data' => $data]);
            $connection->lastMessageTime = time();
            $message = json_decode($data, true);

            // 处理消息类型
            switch ($message['type'] ?? '') {
                case 'join':
                    // 用户加入
                    $connection->username = $message['username'];
                    self::$connections[$connection->id] = $connection;

                    // 广播用户加入
                    $this->broadcast([
                        'type' => 'system',
                        'message' => "{$message['username']} 加入了聊天室",
                        'time' => date('H:i')
                    ], $connection->id);
                    break;

                case 'chat':
                    // 聊天消息
                    if (!isset($connection->username)) {
                        $connection->send(json_encode([
                            'type' => 'system',
                            'message' => '请先设置昵称',
                            'time' => date('H:i')
                        ]));
                        return;
                    }

                    // 构建完整的消息
                    $broadcastMessage = [
                        'type' => 'chat',
                        'username' => $connection->username,
                        'message' => $message['message'],
                        'time' => date('H:i')
                    ];

                    $this->broadcast($broadcastMessage);
                    break;
            }
           // Worker::runAll();
        };

        // 连接关闭
        $ws_worker->onClose = function (TcpConnection $connection) {
            $ip = $connection->getRemoteIp();
            $port = $connection->getRemotePort();
            $connectionId = "$ip:$port";
            if (isset($connection->username)) {
                // 广播用户离开
                $this->broadcast([
                    'type' => 'system',
                    'message' => "{$connection->username} 离开了聊天室",
                    'time' => date('H:i')
                ]);
            }

            // 从连接池移除
            unset(self::$connections[$connection->id]);
            unset(self::$connectionMap[$connectionId]);
        };

        // 心跳检测
        Timer::add(10, function() use ($ws_worker) {
            $now = time();
            foreach ($ws_worker->connections as $connection) {
                if ($now - $connection->lastMessageTime > HEARTBEAT_INTERVAL) {
                    $connection->close();
                }
            }
        });
        Log::channel('timer')->info("WebSocket方法end", ['end' => date('YmdHi')]);
    }

    // 广播消息给所有客户端
    private function broadcast(array $message, $excludeId = null)
    {
        // 确保消息包含所有必要字段
        if ($message['type'] == 'chat') {
            $message = array_merge([
                'username' => '系统',
                'time' => date('H:i')
            ], $message);
        }

        // 确保系统消息也有时间
        if ($message['type'] == 'system' && !isset($message['time'])) {
            $message['time'] = date('H:i');
        }

        $json = json_encode($message);
        Log::channel('timer')->info("broadcast", ['broadcast' => $message]);

        foreach (self::$connections as $id => $connection) {
            // 排除特定连接
            if ($excludeId !== null && $id === $excludeId) continue;

            try {
                $connection->send($json);
            } catch (\Exception $e) {
                // 忽略发送失败
            }
        }
    }

}
148 2 0
2个回答

落落

kof21411

nginx 里做 ssl转发

  • 暂无评论
🔝