test_websocket.html 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>WebSocket 连接测试</title>
  7. <style>
  8. body {
  9. font-family: Arial, sans-serif;
  10. margin: 20px;
  11. background-color: #f5f5f5;
  12. }
  13. .container {
  14. max-width: 800px;
  15. margin: 0 auto;
  16. background: white;
  17. padding: 20px;
  18. border-radius: 10px;
  19. box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  20. }
  21. button {
  22. background-color: #007bff;
  23. color: white;
  24. border: none;
  25. padding: 10px 20px;
  26. border-radius: 5px;
  27. cursor: pointer;
  28. margin: 5px;
  29. }
  30. button:hover {
  31. background-color: #0056b3;
  32. }
  33. button:disabled {
  34. background-color: #ccc;
  35. cursor: not-allowed;
  36. }
  37. .status {
  38. padding: 10px;
  39. margin: 10px 0;
  40. border-radius: 5px;
  41. }
  42. .success {
  43. background-color: #d4edda;
  44. color: #155724;
  45. border: 1px solid #c3e6cb;
  46. }
  47. .error {
  48. background-color: #f8d7da;
  49. color: #721c24;
  50. border: 1px solid #f5c6cb;
  51. }
  52. .info {
  53. background-color: #d1ecf1;
  54. color: #0c5460;
  55. border: 1px solid #bee5eb;
  56. }
  57. #log {
  58. background-color: #f8f9fa;
  59. border: 1px solid #dee2e6;
  60. padding: 15px;
  61. max-height: 400px;
  62. overflow-y: auto;
  63. font-family: monospace;
  64. font-size: 12px;
  65. margin-top: 20px;
  66. }
  67. .log-entry {
  68. margin: 5px 0;
  69. padding: 2px 0;
  70. border-bottom: 1px dotted #ccc;
  71. }
  72. .timestamp {
  73. color: #666;
  74. font-weight: bold;
  75. }
  76. .log-error {
  77. color: #dc3545;
  78. }
  79. .log-success {
  80. color: #28a745;
  81. }
  82. .log-info {
  83. color: #17a2b8;
  84. }
  85. </style>
  86. </head>
  87. <body>
  88. <div class="container">
  89. <h1>🔗 WebSocket 连接测试工具</h1>
  90. <div class="controls">
  91. <button id="connectBtn" onclick="connectWebSocket()">连接 WebSocket</button>
  92. <button id="disconnectBtn" onclick="disconnectWebSocket()" disabled>断开连接</button>
  93. <button id="sendPingBtn" onclick="sendPing()" disabled>发送 Ping</button>
  94. <button id="clearLogBtn" onclick="clearLog()">清空日志</button>
  95. </div>
  96. <div id="status" class="status info">
  97. 准备连接到 ws://localhost:8765/
  98. </div>
  99. <div id="log">
  100. <div class="log-entry">
  101. <span class="timestamp">[系统]</span> WebSocket 测试工具已初始化
  102. </div>
  103. </div>
  104. </div>
  105. <script>
  106. let ws = null;
  107. let reconnectAttempts = 0;
  108. const maxReconnectAttempts = 5;
  109. const reconnectDelay = 2000;
  110. function log(message, type = 'info') {
  111. const logDiv = document.getElementById('log');
  112. const timestamp = new Date().toLocaleTimeString();
  113. const entry = document.createElement('div');
  114. entry.className = `log-entry log-${type}`;
  115. entry.innerHTML = `<span class="timestamp">[${timestamp}]</span> ${message}`;
  116. logDiv.appendChild(entry);
  117. logDiv.scrollTop = logDiv.scrollHeight;
  118. }
  119. function updateStatus(message, type = 'info') {
  120. const statusDiv = document.getElementById('status');
  121. statusDiv.textContent = message;
  122. statusDiv.className = `status ${type}`;
  123. }
  124. function updateButtons(connected) {
  125. document.getElementById('connectBtn').disabled = connected;
  126. document.getElementById('disconnectBtn').disabled = !connected;
  127. document.getElementById('sendPingBtn').disabled = !connected;
  128. }
  129. function connectWebSocket() {
  130. try {
  131. log('尝试连接到 ws://localhost:8765/', 'info');
  132. updateStatus('正在连接...', 'info');
  133. ws = new WebSocket('ws://localhost:8765/');
  134. // 连接超时处理
  135. const connectionTimeout = setTimeout(() => {
  136. if (ws && ws.readyState === WebSocket.CONNECTING) {
  137. log('连接超时,正在关闭连接', 'error');
  138. ws.close();
  139. }
  140. }, 10000);
  141. ws.onopen = function(event) {
  142. clearTimeout(connectionTimeout);
  143. reconnectAttempts = 0;
  144. log('✅ WebSocket 连接成功!', 'success');
  145. updateStatus('已连接', 'success');
  146. updateButtons(true);
  147. // 发送初始消息
  148. const initMessage = {
  149. type: 'ping',
  150. timestamp: Date.now()
  151. };
  152. ws.send(JSON.stringify(initMessage));
  153. log(`📤 发送初始 ping: ${JSON.stringify(initMessage)}`, 'info');
  154. };
  155. ws.onmessage = function(event) {
  156. log(`📥 收到消息: ${event.data}`, 'success');
  157. try {
  158. const data = JSON.parse(event.data);
  159. if (data.type === 'pong') {
  160. log('🏓 收到 pong 响应', 'success');
  161. }
  162. } catch (e) {
  163. log('收到非JSON格式消息', 'info');
  164. }
  165. };
  166. ws.onerror = function(error) {
  167. clearTimeout(connectionTimeout);
  168. log(`❌ WebSocket 错误: ${error.message || '未知错误'}`, 'error');
  169. log(`错误详情: ${JSON.stringify(error)}`, 'error');
  170. updateStatus('连接错误', 'error');
  171. updateButtons(false);
  172. };
  173. ws.onclose = function(event) {
  174. clearTimeout(connectionTimeout);
  175. log(`🔌 WebSocket 连接关闭. Code: ${event.code}, Reason: ${event.reason || '无原因'}`, 'error');
  176. updateStatus(`连接已关闭 (${event.code})`, 'error');
  177. updateButtons(false);
  178. // 自动重连逻辑
  179. if (reconnectAttempts < maxReconnectAttempts && event.code !== 1000) {
  180. reconnectAttempts++;
  181. log(`🔄 ${reconnectDelay/1000}秒后尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})`, 'info');
  182. setTimeout(() => {
  183. connectWebSocket();
  184. }, reconnectDelay);
  185. } else if (reconnectAttempts >= maxReconnectAttempts) {
  186. log('🚫 达到最大重连次数,停止重连', 'error');
  187. }
  188. };
  189. } catch (error) {
  190. log(`❌ 创建 WebSocket 连接时出错: ${error.message}`, 'error');
  191. updateStatus('创建连接失败', 'error');
  192. updateButtons(false);
  193. }
  194. }
  195. function disconnectWebSocket() {
  196. if (ws) {
  197. log('主动断开 WebSocket 连接', 'info');
  198. ws.close(1000, '用户主动断开');
  199. ws = null;
  200. }
  201. }
  202. function sendPing() {
  203. if (ws && ws.readyState === WebSocket.OPEN) {
  204. const pingMessage = {
  205. type: 'ping',
  206. timestamp: Date.now(),
  207. test: true
  208. };
  209. ws.send(JSON.stringify(pingMessage));
  210. log(`📤 发送 ping: ${JSON.stringify(pingMessage)}`, 'info');
  211. } else {
  212. log('❌ WebSocket 未连接,无法发送消息', 'error');
  213. }
  214. }
  215. function clearLog() {
  216. const logDiv = document.getElementById('log');
  217. logDiv.innerHTML = '<div class="log-entry"><span class="timestamp">[系统]</span> 日志已清空</div>';
  218. }
  219. // 页面加载完成后的初始化
  220. window.addEventListener('load', function() {
  221. log('页面加载完成,可以开始测试', 'info');
  222. updateButtons(false);
  223. });
  224. // 页面关闭前清理
  225. window.addEventListener('beforeunload', function() {
  226. if (ws) {
  227. ws.close();
  228. }
  229. });
  230. </script>
  231. </body>
  232. </html>