js实现多人聊天
实现多人聊天室的基本步骤
使用 WebSocket 技术可以实现实时多人聊天功能。以下是一个基于 Node.js 和 Socket.io 的实现方案:
服务端搭建(Node.js + Socket.io)
安装依赖:

npm install express socket.io
创建服务端代码(server.js):
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('新用户连接');
socket.on('join', (username) => {
socket.username = username;
io.emit('message', { user: '系统', text: `${username} 加入了聊天室` });
});
socket.on('chat message', (msg) => {
io.emit('message', { user: socket.username, text: msg });
});
socket.on('disconnect', () => {
if (socket.username) {
io.emit('message', { user: '系统', text: `${socket.username} 离开了聊天室` });
}
});
});
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
客户端实现
创建HTML文件(public/index.html):

<!DOCTYPE html>
<html>
<head>
<title>多人聊天室</title>
<style>
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 8px 16px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="username" autocomplete="off" placeholder="输入用户名" />
<input id="input" autocomplete="off" placeholder="输入消息" />
<button>发送</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const form = document.getElementById('form');
const input = document.getElementById('input');
const usernameInput = document.getElementById('username');
const messages = document.getElementById('messages');
usernameInput.addEventListener('change', () => {
if (usernameInput.value) {
socket.emit('join', usernameInput.value);
usernameInput.disabled = true;
}
});
form.addEventListener('submit', (e) => {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('message', (data) => {
const item = document.createElement('li');
item.textContent = `${data.user}: ${data.text}`;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
</body>
</html>
运行聊天室
启动服务器:
node server.js
打开多个浏览器窗口访问 http://localhost:3000 即可测试多人聊天功能。
功能扩展建议
- 添加私聊功能:可以通过特定命令实现用户间私密消息
- 用户列表显示:维护在线用户列表并实时更新
- 消息历史记录:将消息存储到数据库实现历史查询
- 房间功能:允许用户创建和加入不同主题的聊天室
- 文件共享:扩展支持图片和文件传输
这个实现使用了Socket.io库,它封装了WebSocket并提供了更简单的API和自动重连等功能,适合快速开发实时应用。






