目录
十二、WebSocket 聊天系统与 REST API 协同架构

一、核心原理:全双工通信模型
WebSocket 与 HTTP 不同,它是 TCP 长连接 的 全双工通道(Full Duplex Channel)。 即 —— 连接建立后,客户端与服务器双方都能主动发消息。
HTTP 握手 → 协议升级 (101 Switching Protocols)
↓
建立 WebSocket 长连接
↓
双向消息流:Client ↔ Server
典型事件流如下:
客户端发送 → Server 广播 → 其他客户端接收
Server 发送 → Client 接收并渲染
二、系统架构设计
1. 模块划分
| 模块 | 职责 |
| 客户端(Web/移动端) | 建立连接、发送消息、渲染 UI |
| WebSocket 网关 | 管理连接、转发消息、维护用户会话 |
| 消息服务 | 处理消息路由、存储、历史记录 |
| 数据库 | 持久化聊天记录、用户状态 |
| Redis / MQ | 实现多节点广播与分布式会话同步 |
2. 架构图(逻辑流程)
三、浏览器端 API 实现
基础客户端逻辑
const ws = new WebSocket("wss://chat.example.com/ws");
ws.onopen = () => console.log("Connected to chat server");
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "chat") renderMessage(msg);
};
function sendMessage(to, text) {
ws.send(JSON.stringify({
type: "chat",
from: "userA",
to,
text,
timestamp: Date.now()
}));
}
自动重连与心跳机制
let reconnectTimer;
function connect() {
const ws = new WebSocket("wss://chat.example.com/ws");
ws.onopen = () => {
console.log("Connected");
setInterval(() => ws.send(JSON.stringify({ type: "ping" })), 30000);
};
ws.onclose = () => {
console.log("Reconnecting...");
clearTimeout(reconnectTimer);
reconnectTimer = setTimeout(connect, 5000);
};
}
connect();
四、服务端实现(Node.js 示例)
基于 ws 模块实现
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
const clients = new Map(); // userId -> ws
wss.on("connection", (ws, req) => {
const userId = new URL(req.url, "http://localhost").searchParams.get("user");
clients.set(userId, ws);
ws.on("message", (msg) => {
const data = JSON.parse(msg);
if (data.type === "chat") {
const target = clients.get(data.to);
if (target && target.readyState === 1) {
target.send(JSON.stringify({
type: "chat",
from: data.from,
text: data.text,
timestamp: Date.now()
}));
}
}
});
ws.on("close", () => clients.delete(userId));
});

最低0.47元/天 解锁文章
1356

被折叠的 条评论
为什么被折叠?



