| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255 |
- <!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;
- margin: 20px;
- background-color: #f5f5f5;
- }
- .container {
- max-width: 800px;
- margin: 0 auto;
- background: white;
- padding: 20px;
- border-radius: 10px;
- box-shadow: 0 2px 10px rgba(0,0,0,0.1);
- }
- button {
- background-color: #007bff;
- color: white;
- border: none;
- padding: 10px 20px;
- border-radius: 5px;
- cursor: pointer;
- margin: 5px;
- }
- button:hover {
- background-color: #0056b3;
- }
- button:disabled {
- background-color: #ccc;
- cursor: not-allowed;
- }
- .status {
- padding: 10px;
- margin: 10px 0;
- border-radius: 5px;
- }
- .success {
- background-color: #d4edda;
- color: #155724;
- border: 1px solid #c3e6cb;
- }
- .error {
- background-color: #f8d7da;
- color: #721c24;
- border: 1px solid #f5c6cb;
- }
- .info {
- background-color: #d1ecf1;
- color: #0c5460;
- border: 1px solid #bee5eb;
- }
- #log {
- background-color: #f8f9fa;
- border: 1px solid #dee2e6;
- padding: 15px;
- max-height: 400px;
- overflow-y: auto;
- font-family: monospace;
- font-size: 12px;
- margin-top: 20px;
- }
- .log-entry {
- margin: 5px 0;
- padding: 2px 0;
- border-bottom: 1px dotted #ccc;
- }
- .timestamp {
- color: #666;
- font-weight: bold;
- }
- .log-error {
- color: #dc3545;
- }
- .log-success {
- color: #28a745;
- }
- .log-info {
- color: #17a2b8;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <h1>🔗 WebSocket 连接测试工具</h1>
-
- <div class="controls">
- <button id="connectBtn" onclick="connectWebSocket()">连接 WebSocket</button>
- <button id="disconnectBtn" onclick="disconnectWebSocket()" disabled>断开连接</button>
- <button id="sendPingBtn" onclick="sendPing()" disabled>发送 Ping</button>
- <button id="clearLogBtn" onclick="clearLog()">清空日志</button>
- </div>
-
- <div id="status" class="status info">
- 准备连接到 ws://localhost:8765/
- </div>
-
- <div id="log">
- <div class="log-entry">
- <span class="timestamp">[系统]</span> WebSocket 测试工具已初始化
- </div>
- </div>
- </div>
- <script>
- let ws = null;
- let reconnectAttempts = 0;
- const maxReconnectAttempts = 5;
- const reconnectDelay = 2000;
- function log(message, type = 'info') {
- const logDiv = document.getElementById('log');
- const timestamp = new Date().toLocaleTimeString();
- const entry = document.createElement('div');
- entry.className = `log-entry log-${type}`;
- entry.innerHTML = `<span class="timestamp">[${timestamp}]</span> ${message}`;
- logDiv.appendChild(entry);
- logDiv.scrollTop = logDiv.scrollHeight;
- }
- function updateStatus(message, type = 'info') {
- const statusDiv = document.getElementById('status');
- statusDiv.textContent = message;
- statusDiv.className = `status ${type}`;
- }
- function updateButtons(connected) {
- document.getElementById('connectBtn').disabled = connected;
- document.getElementById('disconnectBtn').disabled = !connected;
- document.getElementById('sendPingBtn').disabled = !connected;
- }
- function connectWebSocket() {
- try {
- log('尝试连接到 ws://localhost:8765/', 'info');
- updateStatus('正在连接...', 'info');
-
- ws = new WebSocket('ws://localhost:8765/');
-
- // 连接超时处理
- const connectionTimeout = setTimeout(() => {
- if (ws && ws.readyState === WebSocket.CONNECTING) {
- log('连接超时,正在关闭连接', 'error');
- ws.close();
- }
- }, 10000);
- ws.onopen = function(event) {
- clearTimeout(connectionTimeout);
- reconnectAttempts = 0;
- log('✅ WebSocket 连接成功!', 'success');
- updateStatus('已连接', 'success');
- updateButtons(true);
-
- // 发送初始消息
- const initMessage = {
- type: 'ping',
- timestamp: Date.now()
- };
- ws.send(JSON.stringify(initMessage));
- log(`📤 发送初始 ping: ${JSON.stringify(initMessage)}`, 'info');
- };
- ws.onmessage = function(event) {
- log(`📥 收到消息: ${event.data}`, 'success');
-
- try {
- const data = JSON.parse(event.data);
- if (data.type === 'pong') {
- log('🏓 收到 pong 响应', 'success');
- }
- } catch (e) {
- log('收到非JSON格式消息', 'info');
- }
- };
- ws.onerror = function(error) {
- clearTimeout(connectionTimeout);
- log(`❌ WebSocket 错误: ${error.message || '未知错误'}`, 'error');
- log(`错误详情: ${JSON.stringify(error)}`, 'error');
- updateStatus('连接错误', 'error');
- updateButtons(false);
- };
- ws.onclose = function(event) {
- clearTimeout(connectionTimeout);
- log(`🔌 WebSocket 连接关闭. Code: ${event.code}, Reason: ${event.reason || '无原因'}`, 'error');
- updateStatus(`连接已关闭 (${event.code})`, 'error');
- updateButtons(false);
-
- // 自动重连逻辑
- if (reconnectAttempts < maxReconnectAttempts && event.code !== 1000) {
- reconnectAttempts++;
- log(`🔄 ${reconnectDelay/1000}秒后尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})`, 'info');
- setTimeout(() => {
- connectWebSocket();
- }, reconnectDelay);
- } else if (reconnectAttempts >= maxReconnectAttempts) {
- log('🚫 达到最大重连次数,停止重连', 'error');
- }
- };
- } catch (error) {
- log(`❌ 创建 WebSocket 连接时出错: ${error.message}`, 'error');
- updateStatus('创建连接失败', 'error');
- updateButtons(false);
- }
- }
- function disconnectWebSocket() {
- if (ws) {
- log('主动断开 WebSocket 连接', 'info');
- ws.close(1000, '用户主动断开');
- ws = null;
- }
- }
- function sendPing() {
- if (ws && ws.readyState === WebSocket.OPEN) {
- const pingMessage = {
- type: 'ping',
- timestamp: Date.now(),
- test: true
- };
- ws.send(JSON.stringify(pingMessage));
- log(`📤 发送 ping: ${JSON.stringify(pingMessage)}`, 'info');
- } else {
- log('❌ WebSocket 未连接,无法发送消息', 'error');
- }
- }
- function clearLog() {
- const logDiv = document.getElementById('log');
- logDiv.innerHTML = '<div class="log-entry"><span class="timestamp">[系统]</span> 日志已清空</div>';
- }
- // 页面加载完成后的初始化
- window.addEventListener('load', function() {
- log('页面加载完成,可以开始测试', 'info');
- updateButtons(false);
- });
- // 页面关闭前清理
- window.addEventListener('beforeunload', function() {
- if (ws) {
- ws.close();
- }
- });
- </script>
- </body>
- </html>
|