前端聊天室
<!DOCTYPE html> <html> <head> <title>Socket.IO 聊天室</title> <script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script> <style> .chat-box { height: 400px; border: 1px solid #ccc; overflow-y: auto; padding: 10px; } .message { margin: 8px 0; padding: 8px; border-radius: 4px; } .self { background: #e3f2fd; margin-left: 20%; } .others { background: #f5f5f5; margin-right: 20%; } #user-list { position: fixed; right: 20px; top: 20px; background: white; padding: 10px; border: 1px solid #ddd; } </style> </head> <body> <div id="user-list"></div> <div class="chat-box" id="chatBox"></div> <input type="text" id="messageInput" placeholder="输入消息..." style="width: 70%"> <button onclick="sendMessage()">发送</button> <script> // 初始化连接 const socket = io('wss://your-chat-server.com', { auth: { userId: localStorage.getItem('userId') || `user_${Date.now()}` }, reconnectionAttempts: 3, transports: ['websocket'] }); // 消息发送函数 function sendMessage() { const input = document.getElementById('messageInput'); if (input.value.trim()) { socket.emit('chatMessage', { text: input.value, time: new Date().toISOString() }); input.value = ''; } } // 监听服务端消息 socket.on('chatMessage', (msg) => { const isSelf = msg.userId === socket.auth.userId; const div = document.createElement('div'); div.className = `message ${isSelf ? 'self' : 'others'}`; div.innerHTML = `<b>${msg.nickname}</b>: ${msg.text}<br><small>${new Date(msg.time).toLocaleTimeString()}</small>`; document.getElementById('chatBox').appendChild(div); }); // 用户列表更新 socket.on('userListUpdate', (users) => { document.getElementById('user-list').innerHTML = `<h4>在线用户 (${users.length})</h4>` + users.map(u => `<div>${u.nickname}</div>`).join(''); }); // 连接状态管理 socket.on('connect', () => { console.log('已连接服务器'); socket.emit('joinRoom', 'public'); }); socket.on('disconnect', () => { console.warn('连接已断开'); }); // 回车发送 document.getElementById('messageInput').addEventListener('keypress', (e) => { if (e.key === 'Enter') sendMessage(); }); </script> </body> </html>
二、核心功能说明
连接配置
自动生成用户 ID 并存储于
localStorage
优先使用 WebSocket 协议,失败后自动重连
消息交互
支持文本消息发送与格式化时间显示
消息气泡区分自己/他人(CSS 样式控制)
状态管理
实时更新在线用户列表
自动加入默认公共聊天室
public
三、服务端需配合实现
虽然此示例为纯前端代码,但需服务端支持以下逻辑:
处理
joinRoom
事件管理房间广播
chatMessage
到同一房间用户维护用户连接状态并推送
userListUpdate
四、扩展建议
历史记录
添加localStorage
缓存最近的 100 条消息文件传输
通过socket.emit('fileUpload', base64Data)
实现(需服务端支持)心跳检测
增加setInterval
发送心跳包维持连接