WebSocket 的使用
创建 WebSocket 连接// 创建 WebSocket 连接 const socket new WebSocket(ws://localhost:8080); // 或者使用安全连接 const secureSocket new WebSocket(wss://example.com/socket);2. WebSocket 事件// 连接建立时触发 socket.onopen function(event) { console.log(连接已建立); socket.send(Hello Server!); }; // 接收到消息时触发 socket.onmessage function(event) { console.log(收到消息:, event.data); // 处理接收到的数据 }; // 发生错误时触发 socket.onerror function(error) { console.error(WebSocket 错误:, error); }; // 连接关闭时触发 socket.onclose function(event) { console.log(连接关闭, event.code, event.reason); // 可以在这里尝试重连 };完整示例客户端示例!DOCTYPE html html head titleWebSocket 示例/title /head body div input typetext idmessageInput placeholder输入消息 button onclicksendMessage()发送/button /div div idmessages/div script // 创建 WebSocket 连接 const socket new WebSocket(ws://localhost:8080); const messagesDiv document.getElementById(messages); // 连接建立 socket.onopen function() { addMessage(系统, 连接成功); }; // 接收消息 socket.onmessage function(event) { try { const data JSON.parse(event.data); addMessage(data.sender, data.message); } catch (e) { addMessage(系统, event.data); } }; // 错误处理 socket.onerror function(error) { addMessage(系统, 连接错误); }; // 连接关闭 socket.onclose function() { addMessage(系统, 连接已关闭); }; // 发送消息 function sendMessage() { const input document.getElementById(messageInput); const message input.value.trim(); if (message) { socket.send(JSON.stringify({ type: message, content: message, timestamp: new Date().toISOString() })); input.value ; } } // 显示消息 function addMessage(sender, text) { const msgElement document.createElement(div); msgElement.innerHTML strong${sender}:/strong ${text}; messagesDiv.appendChild(msgElement); messagesDiv.scrollTop messagesDiv.scrollHeight; } // 关闭连接页面卸载时 window.addEventListener(beforeunload, function() { if (socket.readyState WebSocket.OPEN) { socket.close(1000, 用户离开页面); } }); /script /body /htmlNode.js 服务器端示例// 使用 ws 库 const WebSocket require(ws); // 创建 WebSocket 服务器 const wss new WebSocket.Server({ port: 8080 }); console.log(WebSocket 服务器启动在 ws://localhost:8080); // 连接处理 wss.on(connection, function connection(ws) { console.log(新客户端连接); // 发送欢迎消息 ws.send(JSON.stringify({ type: system, message: 欢迎连接到服务器 })); // 接收客户端消息 ws.on(message, function incoming(message) { console.log(收到消息:, message); try { const data JSON.parse(message); // 广播消息给所有客户端 wss.clients.forEach(function each(client) { if (client ! ws client.readyState WebSocket.OPEN) { client.send(JSON.stringify({ type: message, sender: 用户, message: data.content, timestamp: new Date().toISOString() })); } }); } catch (error) { console.error(消息解析错误:, error); } }); // 连接关闭 ws.on(close, function() { console.log(客户端断开连接); }); // 错误处理 ws.on(error, function(error) { console.error(WebSocket 错误:, error); }); });WebSocket 状态// 检查连接状态 switch(socket.readyState) { case WebSocket.CONNECTING: // 0 - 连接中 console.log(连接中...); break; case WebSocket.OPEN: // 1 - 已连接 console.log(已连接); break; case WebSocket.CLOSING: // 2 - 关闭中 console.log(正在关闭...); break; case WebSocket.CLOSED: // 3 - 已关闭 console.log(已关闭); break; }高级特性1. 心跳检测// 心跳检测 let heartbeatInterval; socket.onopen function() { console.log(连接建立); // 开始心跳 heartbeatInterval setInterval(() { if (socket.readyState WebSocket.OPEN) { socket.send(JSON.stringify({ type: ping })); } }, 30000); }; socket.onclose function() { // 清除心跳 clearInterval(heartbeatInterval); };2. 重连机制class WebSocketClient { constructor(url) { this.url url; this.socket null; this.reconnectAttempts 0; this.maxReconnectAttempts 5; this.reconnectDelay 1000; } connect() { this.socket new WebSocket(this.url); this.socket.onopen () { console.log(连接成功); this.reconnectAttempts 0; }; this.socket.onclose (event) { console.log(连接断开尝试重连...); this.reconnect(); }; this.socket.onerror (error) { console.error(连接错误:, error); }; } reconnect() { if (this.reconnectAttempts this.maxReconnectAttempts) { this.reconnectAttempts; const delay this.reconnectDelay * Math.pow(2, this.reconnectAttempts); setTimeout(() { console.log(第 ${this.reconnectAttempts} 次重连); this.connect(); }, delay); } else { console.error(重连次数已达上限); } } send(data) { if (this.socket.readyState WebSocket.OPEN) { this.socket.send(data); } } }3. 二进制数据传输// 发送二进制数据 socket.onopen function() { // 发送 ArrayBuffer const buffer new ArrayBuffer(4); const view new Uint8Array(buffer); view[0] 1; view[1] 2; view[2] 3; view[3] 4; socket.send(buffer); // 发送 Blob const blob new Blob([Hello], { type: text/plain }); socket.send(blob); }; // 接收二进制数据 socket.binaryType arraybuffer; // 或 blob socket.onmessage function(event) { if (event.data instanceof ArrayBuffer) { // 处理 ArrayBuffer const view new Uint8Array(event.data); console.log(收到二进制数据:, view); } else { // 处理文本数据 console.log(收到文本数据:, event.data); } };Spring Boot 中使用 WebSocket添加依赖dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-websocket/artifactId /dependency基础配置类Configuration EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { Override public void configureMessageBroker(MessageBrokerRegistry config) { // 消息代理前缀 config.enableSimpleBroker(/topic, /queue); // 应用目的地前缀 config.setApplicationDestinationPrefixes(/app); // 用户目的地前缀一对一消息 config.setUserDestinationPrefix(/user); } Override public void registerStompEndpoints(StompEndpointRegistry registry) { // 注册 WebSocket 端点 registry.addEndpoint(/ws) .setAllowedOriginPatterns(*) .withSockJS(); // 支持 SockJS 降级 // 也可以添加多个端点 registry.addEndpoint(/ws-native) .setAllowedOriginPatterns(*); } Override public void configureWebSocketTransport(WebSocketTransportRegistration registration) { // 配置传输限制 registration.setMessageSizeLimit(128 * 1024); // 消息大小限制 128KB registration.setSendTimeLimit(20 * 1000); // 发送超时 20秒 registration.setSendBufferSizeLimit(512 * 1024); // 发送缓冲区限制 512KB } }

相关新闻