websocket_test.html 8.95 KB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket通信测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .message-form {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        .message-form input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .message-form button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .message-form button:hover {
            background-color: #0056b3;
        }
        .log {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            height: 300px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }
        .log-entry {
            margin-bottom: 5px;
            padding: 2px 0;
        }
        .log-entry.info {
            color: #0066cc;
        }
        .log-entry.error {
            color: #cc0000;
        }
        .log-entry.success {
            color: #009900;
        }
    </style>
</head>
<body>
    <h1>WebSocket通信测试</h1>
    
    <div class="container">
        <h3>连接状态</h3>
        <div id="status" class="status disconnected">未连接</div>
        <button id="connectBtn" onclick="connect()">连接</button>
        <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
    </div>
    
    <div class="container">
        <h3>发送消息测试</h3>
        <div class="message-form">
            <input type="number" id="sessionid" placeholder="会话ID" value="0">
            <select id="messageType">
                <option value="chat">智能对话</option>
                <option value="echo">回音模式</option>
            </select>
            <input type="text" id="messageText" placeholder="输入消息内容">
            <button onclick="sendMessage()">发送到/human接口</button>
        </div>
    </div>
    
    <div class="container">
        <h3>消息日志</h3>
        <button onclick="clearLog()">清空日志</button>
        <div id="log" class="log"></div>
    </div>

    <script>
        let ws = null;
        let reconnectAttempts = 0;
        const maxReconnectAttempts = 5;
        
        function addLog(message, type = 'info') {
            const log = document.getElementById('log');
            const entry = document.createElement('div');
            entry.className = `log-entry ${type}`;
            const timestamp = new Date().toLocaleTimeString();
            entry.textContent = `[${timestamp}] ${message}`;
            log.appendChild(entry);
            log.scrollTop = log.scrollHeight;
        }
        
        function updateStatus(connected) {
            const status = document.getElementById('status');
            const connectBtn = document.getElementById('connectBtn');
            const disconnectBtn = document.getElementById('disconnectBtn');
            
            if (connected) {
                status.textContent = '已连接';
                status.className = 'status connected';
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
            } else {
                status.textContent = '未连接';
                status.className = 'status disconnected';
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
            }
        }
        
        function connect() {
            const host = window.location.hostname;
            const port = '8010';
            const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
            const wsUrl = `${protocol}${host}:${port}/ws`;
            
            addLog(`尝试连接到: ${wsUrl}`);
            
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function() {
                addLog('WebSocket连接成功', 'success');
                updateStatus(true);
                reconnectAttempts = 0;
                
                // 发送登录消息
                const sessionid = parseInt(document.getElementById('sessionid').value) || 0;
                const loginMessage = {
                    type: 'login',
                    sessionid: sessionid,
                    username: 'TestUser'
                };
                ws.send(JSON.stringify(loginMessage));
                addLog(`发送登录消息: ${JSON.stringify(loginMessage)}`);
            };
            
            ws.onmessage = function(e) {
                addLog(`收到消息: ${e.data}`, 'success');
                
                try {
                    const messageData = JSON.parse(e.data);
                    
                    if (messageData.type === 'chat_message') {
                        const data = messageData.data;
                        addLog(`聊天消息 - 来源: ${data.source}, 类型: ${data.message_type}, 内容: ${data.content}`, 'success');
                    } else if (messageData.type === 'login_success') {
                        addLog(`登录成功: ${messageData.message}`, 'success');
                    } else if (messageData.type === 'pong') {
                        addLog('收到心跳响应', 'info');
                    }
                } catch (err) {
                    addLog(`解析消息失败: ${err.message}`, 'error');
                }
            };
            
            ws.onclose = function(e) {
                addLog(`WebSocket连接关闭: ${e.code} - ${e.reason}`, 'error');
                updateStatus(false);
                
                // 自动重连
                if (reconnectAttempts < maxReconnectAttempts) {
                    reconnectAttempts++;
                    addLog(`尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})...`);
                    setTimeout(connect, 3000);
                }
            };
            
            ws.onerror = function(e) {
                addLog('WebSocket连接错误', 'error');
            };
        }
        
        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }
        
        async function sendMessage() {
            const sessionid = parseInt(document.getElementById('sessionid').value) || 0;
            const messageType = document.getElementById('messageType').value;
            const messageText = document.getElementById('messageText').value;
            
            if (!messageText.trim()) {
                addLog('请输入消息内容', 'error');
                return;
            }
            
            const payload = {
                sessionid: sessionid,
                type: messageType,
                text: messageText
            };
            
            addLog(`发送到/human接口: ${JSON.stringify(payload)}`);
            
            try {
                const response = await fetch('/human', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload)
                });
                
                const result = await response.json();
                addLog(`/human接口响应: ${JSON.stringify(result)}`, response.ok ? 'success' : 'error');
                
                // 清空输入框
                document.getElementById('messageText').value = '';
                
            } catch (err) {
                addLog(`发送失败: ${err.message}`, 'error');
            }
        }
        
        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }
        
        // 页面加载时自动连接
        window.onload = function() {
            addLog('页面加载完成,准备测试WebSocket通信');
        };
        
        // 监听回车键发送消息
        document.getElementById('messageText').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>