实现功能:
- 单人私聊(1:1)
- 群聊(rooms/channels)
- 群聊内
@某人(提及)并产生提醒 - 聊天记录(持久化、分页、检索)
- 在线/离线消息处理与离线推送(概要)
- 安全、扩展与性能建议
设计思路 → 数据模型 → WebSocket 事件协议 → 后端(Node.js + Socket.IO + MongoDB)完整示例 → 前端(HTML + JS + socket.io-client)示例 → 进阶与部署关注点
设计思路
传输层:用 WebSocket(建议用 socket.io,简化房间/重连/心跳/跨域等),也可以用原生 ws。
鉴权:登录后返回 JWT(或 session),WebSocket 连接时带 token 验证。
房间模型:
- 私聊:为每对用户建立“私聊房间 id”,例如
dm:<userAId>:<userBId>(id 可按小->大排序避免重复)。 - 群聊:使用
room:<roomId>。
- 私聊:为每对用户建立“私聊房间 id”,例如
消息持久化:消息写入 DB(MongoDB 推荐,文档型适合聊天),并记录
mentions字段数组(被 @ 的用户 id)。@ 实现:客户端在输入实时完成 username 列表(或 uid),发送消息时把消息体中
mentions: [userId...],服务器也进行一次解析检查(防伪)。离线/未读:在写入消息时记录哪些目标用户未读(unread map),或维护
lastReadAt,方便统计未读数与推送。消息拉取/分页:REST API 用
GET /rooms/:id/messages?before=<timestamp|id>&limit=20分页加载历史。通知:当消息中包含某人的 id(mentions),立刻向该用户推送
mention事件(如果在线),或在 DB 中记录未读并配合 Push Notification(APNs/FCM)发送移动通知。扩展/横向:使用 Redis pub/sub 或 socket.io-adapter(redis-adapter)进行多实例事件广播。
数据模型(MongoDB / Mongoose 风格示例)
// User
{
_id: ObjectId,
username: String, // 唯一
displayName: String,
avatarUrl: String,
passwordHash: String,
lastSeenAt: Date,
createdAt: Date
}
// Room
{
_id: ObjectId,
type: "dm" | "group",
members: [ObjectId],
name?: String, // 群名
ownerId?: ObjectId,
createdAt: Date,
meta: {}
}
// Message
{
_id: ObjectId,
roomId: ObjectId,
senderId: ObjectId,
content: String, // 原始文本(可存富文本或 markdown)
contentHtml?: String, // 可选:预渲染后的 html
mentions: [ObjectId], // 被 @ 的用户 id 列表
attachments?: [{ url, type, filename }],
createdAt: Date,
editedAt?: Date,
deleted?: Boolean,
readBy?: [{ userId: ObjectId, at: Date }] // 或在另表维护 read 状态
}WebSocket / 事件协议(建议)
统一使用 JSON 事件对象 { type, payload } 或 socket.io 的事件名方式。下面用 socket.io 事件名表述。
客户端事件(client → server):
auth:连接后发送 token(若用 socket.io 的 auth 选项可省略)。join_room{ roomId }:加入房间(server 验证权限)。leave_room{ roomId }send_message{ roomId, content, mentions: [userId], attachments?: [...] }typing{ roomId, isTyping: true|false }fetch_messages{ roomId, beforeId?, limit? }(也可用 REST)
服务器事件(server → client):
message{ message }(实时下发)message_ack{ tempId, messageId }(可用于客户端回显确认)typing{ roomId, userId, isTyping }mention{ roomId, messageId, fromUserId }(专门的提及提醒)presence{ userId, online }或presence_updatehistory{ messages: [...] }(回应 fetch_messages)error{ code, message }
后端示例(Node.js + Express + Socket.IO + Mongoose)
以下是教学示例,包含密码验证、HTTP/Socket 鉴权、房间成员检查和提及校验;运行前需准备用户和房间数据。生产环境仍需限流、消息幂等和连接/房间权限撤销机制。
先 npm init -y,安装:
npm i express socket.io mongoose jsonwebtoken bcryptjs cors示例 server.js:
// server.js
const express = require('express');
const http = require('http');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { Server } = require('socket.io');
const cors = require('cors');
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) throw new Error('Set JWT_SECRET before starting the demo');
const MONGO = process.env.MONGO || 'mongodb://localhost:27017/chatapp';
const User = mongoose.model('User', new mongoose.Schema({
username: { type: String, unique: true, required: true },
displayName: String,
passwordHash: { type: String, required: true }
}));
const Room = mongoose.model('Room', new mongoose.Schema({
type: { type: String, enum: ['dm', 'group'] },
members: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
name: String
}));
const Message = mongoose.model('Message', new mongoose.Schema({
roomId: { type: mongoose.Schema.Types.ObjectId, ref: 'Room' },
senderId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
content: String,
mentions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
createdAt: { type: Date, default: Date.now }
}));
const app = express();
app.use(cors());
app.use(express.json({ limit: '32kb' }));
const asyncRoute = handler => (req, res, next) =>
Promise.resolve(handler(req, res, next)).catch(next);
function fail(status, message) {
const error = new Error(message);
error.status = status;
throw error;
}
function validId(id) {
return typeof id === 'string' && mongoose.isObjectIdOrHexString(id);
}
async function authenticate(token) {
if (typeof token !== 'string' || !token) fail(401, 'authentication required');
let payload;
try {
payload = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] });
} catch {
fail(401, 'invalid or expired token');
}
if (!validId(payload.userId) || !Number.isFinite(payload.exp)) fail(401, 'invalid token');
const user = await User.findById(payload.userId);
if (!user) fail(401, 'user not found');
return { user, userId: String(user._id), expiresAt: payload.exp * 1000 };
}
async function requireRoom(roomId, userId) {
if (!validId(roomId)) fail(400, 'invalid room id');
const room = await Room.findById(roomId);
if (!room) fail(404, 'room not found');
if (!room.members.some(id => String(id) === userId)) fail(403, 'no permission');
return room;
}
// Prepare users with bcrypt password hashes separately; this is not registration.
app.post('/login', asyncRoute(async (req, res) => {
const { username, password } = req.body || {};
if (typeof username !== 'string' || typeof password !== 'string') {
fail(400, 'username and password required');
}
const user = await User.findOne({ username });
if (!user || !await bcrypt.compare(password, user.passwordHash)) {
fail(401, 'invalid credentials');
}
const token = jwt.sign({ userId: String(user._id) }, JWT_SECRET,
{ algorithm: 'HS256', expiresIn: '1h' });
res.json({ token, user: { _id: user._id, username: user.username } });
}));
// Express routes require their own authentication; io.use does not protect them.
app.get('/rooms/:roomId/messages', asyncRoute(async (req, res) => {
const token = /^Bearer (.+)$/.exec(req.get('Authorization') || '')?.[1];
const { userId } = await authenticate(token);
const { roomId } = req.params;
await requireRoom(roomId, userId);
const requestedLimit = Number(req.query.limit ?? 20);
if (!Number.isInteger(requestedLimit) || requestedLimit < 1) fail(400, 'invalid limit');
const before = req.query.before;
if (before !== undefined && !validId(before)) fail(400, 'invalid cursor');
const query = { roomId };
if (before) query._id = { $lt: before };
const messages = await Message.find(query).sort({ _id: -1 })
.limit(Math.min(50, requestedLimit)).lean();
res.json({ messages: messages.reverse() });
}));
app.use((error, req, res, next) => {
const status = error.status || 500;
res.status(status).json({ error: status === 500 ? 'internal error' : error.message });
});
const server = http.createServer(app);
const io = new Server(server, { cors: { origin: '*' } });
io.use(async (socket, next) => {
try {
socket.data = await authenticate(socket.handshake.auth?.token);
next();
} catch {
next(new Error('authentication failed'));
}
});
io.on('connection', socket => {
const { userId } = socket.data;
socket.join('user:' + userId);
const handle = handler => async (payload = {}) => {
try {
if (Date.now() >= socket.data.expiresAt) fail(401, 'token expired');
if (!payload || typeof payload !== 'object') fail(400, 'invalid payload');
await handler(payload);
} catch (error) {
socket.emit('error', {
code: error.status || 500,
message: error.status ? error.message : 'internal error'
});
}
};
socket.on('join_room', handle(async ({ roomId }) => {
await requireRoom(roomId, userId);
socket.join('room:' + roomId);
socket.emit('joined', { roomId });
}));
socket.on('leave_room', handle(async ({ roomId }) => {
if (!validId(roomId)) fail(400, 'invalid room id');
socket.leave('room:' + roomId);
}));
socket.on('send_message', handle(async ({ roomId, content, mentions = [], tempId }) => {
if (typeof content !== 'string' || !content.trim() || content.length > 10000) {
fail(400, 'invalid content');
}
const room = await requireRoom(roomId, userId);
if (!Array.isArray(mentions) || mentions.length > 50 || !mentions.every(validId)) {
fail(400, 'invalid mentions');
}
const mentionIds = [...new Set(mentions)];
const members = new Set(room.members.map(String));
if (mentionIds.some(id => !members.has(id))) fail(403, 'mention outside room');
const mentionedUsers = await User.find({ _id: { $in: mentionIds } });
if (mentionedUsers.length !== mentionIds.length) fail(400, 'unknown mention');
const escapeRegex = value => value.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&');
for (const user of mentionedUsers) {
const pattern = new RegExp('(^|[^A-Za-z0-9_])@' +
escapeRegex(user.username) + '(?=$|[^A-Za-z0-9_])');
if (!pattern.test(content)) fail(400, 'mention missing from content');
}
const msg = await new Message({
roomId, senderId: userId, content, mentions: mentionIds
}).save();
const message = {
_id: msg._id, roomId, senderId: userId, content,
mentions: mentionIds, createdAt: msg.createdAt
};
io.to('room:' + roomId).emit('message', message);
socket.emit('message_ack', { tempId, messageId: msg._id });
for (const uid of mentionIds) {
io.to('user:' + uid).emit('mention', {
roomId, messageId: msg._id, from: userId, content
});
}
}));
socket.on('typing', handle(async ({ roomId, isTyping }) => {
await requireRoom(roomId, userId);
if (typeof isTyping !== 'boolean') fail(400, 'invalid typing state');
socket.to('room:' + roomId).emit('typing', { roomId, userId, isTyping });
}));
});
async function start() {
await mongoose.connect(MONGO);
server.listen(3000, () => console.log('listening 3000'));
}
start().catch(error => {
console.error(error);
process.exitCode = 1;
});运行方法:
- 启动 MongoDB,准备含 bcrypt passwordHash 的用户及 members 指向用户的房间,设置独立随机 JWT_SECRET 后运行
node server.js。 - 向
POST /login发送 username/password 获得 token;使用io({ auth: { token }})连接,历史请求另带Authorization: Bearer <token>。
前端最小示例(HTML + socket.io-client)
安装:在前端页面引入 socket.io-client(CDN 或 bundler)。
示例 index.html:
<!doctype html>
<html>
<head><meta charset="utf-8"><title>Chat Demo</title></head>
<body>
<div>
<input id="token" placeholder="paste token from /login" style="width:400px"/>
<button id="connectBtn">Connect</button>
</div>
<div id="chat" style="display:none;">
<div>
Room: <input id="roomId" value="" />
<button id="join">Join</button>
</div>
<div id="messages" style="height:300px;overflow:auto;border:1px solid #ccc;padding:8px;"></div>
<div>
<input id="msg" style="width:70%" placeholder="@username to mention" />
<button id="send">Send</button>
</div>
</div>
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
<script>
let socket;
document.getElementById('connectBtn').onclick = () => {
const token = document.getElementById('token').value;
socket = io('http://localhost:3000', { auth: { token }});
socket.on('connect', () => {
console.log('connected', socket.id);
document.getElementById('chat').style.display = 'block';
});
socket.on('message', (m) => {
const el = document.createElement('div');
el.innerText = `[${new Date(m.createdAt).toLocaleTimeString()}] ${m.senderId}: ${m.content}`;
document.getElementById('messages').appendChild(el);
});
socket.on('mention', (x) => {
const el = document.createElement('div');
el.style.background = '#ffc';
el.innerText = `MENTION from ${x.from} in ${x.roomId}: ${x.content}`;
document.getElementById('messages').appendChild(el);
});
};
document.getElementById('join').onclick = () => {
const roomId = document.getElementById('roomId').value;
socket.emit('join_room', { roomId });
};
document.getElementById('send').onclick = () => {
const roomId = document.getElementById('roomId').value;
const content = document.getElementById('msg').value;
// 简化:客户端解析 @username => 替换为 userId (生产需先 resolve username->id)
// 这里示例直接不解析 mentions
socket.emit('send_message', { roomId, content, mentions: [] , tempId: 't'+Date.now()});
};
</script>
</body>
</html>注意:实际生产中,客户端发送消息前 必须 把
@username解析成userId并在mentions数组中传给后端(可通过输入时调用 autocomplete 接口GET /users?query=...)。
@mentions 的实现细节
- 客户端:在输入框实现
@触发 autocomplete,返回匹配用户名与 id(REST:GET /users?query=...)。 - 发送消息:当前示例用
mentions: [userId];如果改为包含位置与用户名的对象,需要同步修改协议和服务端校验。 - 后端:检查发送者和被提及者都是房间成员,并验证正文中的 @username;示例使用基本用户名边界匹配,更复杂的富文本应采用结构化提及节点。
- 通知:若用户离线,推送移动通知或邮件。并在 UI 上显示未读 mention 列表。
存储未读与已读
两种常见方案:
readBy字段内存每个人阅读时间(适合小群);写入成本高于查询成本。user_rooms表维护lastReadAt(或lastReadMessageId),通过比对消息时间/ID 判断未读数(更常见且可扩展)。
安全与性能建议(精通部分)
- 鉴权:WebSocket 握手时强制 jwt 验证;所有 socket 事件在服务器端再做权限检查(不要信任客户端)。
- 速率控制:对
send_message限流,防止刷屏(Redis 令牌桶)。 - 内容过滤:进行敏感词过滤 / XSS 过滤(例如把 contentHtml 用库安全渲染)。
- 防重复/幂等:客户端发消息带
tempId,服务器去重后返回message_ack,客户端替换回临时消息。 - 水平扩展:部署多实例时使用
socket.io-redisadapter,消息与 presence 同步靠 Redis pub/sub。 - 存储与索引:在 Message collection 建立
roomId + createdAt索引,查询历史与分页高效。 - 备份与归档:对过期消息做归档或冷存,避免主库膨胀。
- 消息审计/合规:若有合规需求,保留完整审计日志、删除策略和导出功能。
- 文件/大附件:文件不直接上传 DB,使用 object storage(S3),把元数据与 url 存在 message 文档,并为私有文件生成临时访问 token。
- 隐私:对敏感字段加密(例如某些企业需加密内容)。
进阶功能建议(可选)
- 富文本、表情、回复(引用 messageId)、消息撤回、编辑。
- 在线/离线设备推送(FCM/APNs)。
- 事件溯源(Event sourcing)或 Kafka 消息总线用于复杂场景。
- 搜索(Elasticsearch)用于聊天内容搜索。
- Typing indicator、read receipts(已读回执)、用户在线列表。
- 群管理(邀请、踢出、权限分层、公告、置顶消息)。
部署 & 运维要点
- 在生产用 HTTPS + WSS。
- 多实例部署时,Redis adapter 处理跨节点广播;保留 HTTP long-polling 仍需 sticky session。仅使用 WebSocket 传输等条件下才可省去会话黏性。部署文档。
- 监控:连接数、消息吞吐、延迟、错误率、内存/GC。
- 灰度、回滚策略、日志采集(结构化日志)。