Appearance
WebSocket 实时通信课程计划
课程概述
本课程分为 8 节课,每节课 20-40 分钟,总时长约 120-150 分钟。通过理论讲解和实践操作,深入理解 WebSocket 实时通信的实现方法。
第 1 课:课程介绍与环境准备(5 分钟)
学习目标
- 了解课程内容和目标
- 搭建开发环境
- 项目初始化
课程内容
课程介绍
- WebSocket 的特点
- 实时通信的应用场景
- 课程结构安排
环境准备
- 安装依赖
- 配置开发环境
- 初始化项目
实践操作
bash
# 安装依赖
npm install ws
# 初始化项目
npm init -y预期输出
✅ 依赖安装成功
✅ 项目初始化完成第 2 课:WebSocket 基础(15 分钟)
学习目标
- 理解 WebSocket 协议
- 掌握 WebSocket 服务器和客户端
- 学习 WebSocket 握手过程
课程内容
WebSocket 协议
- 握手过程
- 帧结构
- 操作码
WebSocket 服务器
- 创建服务器
- 处理连接
- 发送和接收消息
WebSocket 客户端
- 连接服务器
- 发送消息
- 接收消息
实践操作
javascript
const WebSocket = require('ws');
// 创建服务器
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log('Received:', message);
ws.send(`Echo: ${message}`);
});
});
console.log('WebSocket server running on port 8080');测试验证
bash
node examples/ws-basic.js预期输出
WebSocket server running on port 8080
Client connected
Received: Hello第 3 课:房间管理(15 分钟)
学习目标
- 理解房间概念
- 实现房间功能
- 学习房间消息广播
课程内容
房间概念
- 房间定义
- 房间用途
- 房间管理
房间功能
- 创建房间
- 加入房间
- 离开房间
房间消息
- 房间广播
- 房间成员管理
- 房间状态同步
实践操作
javascript
class RoomManager {
constructor() {
this.rooms = new Map();
}
joinRoom(clientId, roomName) {
if (!this.rooms.has(roomName)) {
this.rooms.set(roomName, new Set());
}
this.rooms.get(roomName).add(clientId);
}
leaveRoom(clientId, roomName) {
if (this.rooms.has(roomName)) {
this.rooms.get(roomName).delete(clientId);
if (this.rooms.get(roomName).size === 0) {
this.rooms.delete(roomName);
}
}
}
broadcastToRoom(roomName, message, excludeClientId = null) {
const room = this.rooms.get(roomName);
if (!room) return;
room.forEach(clientId => {
if (clientId !== excludeClientId) {
// 发送消息给客户端
}
});
}
}测试验证
bash
node test/rooms.test.js预期输出
✅ Room management tests passed第 4 课:消息处理(15 分钟)
学习目标
- 理解消息类型
- 实现消息路由
- 学习消息验证
课程内容
消息类型
- 文本消息
- 二进制消息
- JSON 消息
消息路由
- 消息解析
- 消息分发
- 消息响应
消息验证
- 格式验证
- 内容验证
- 权限验证
实践操作
javascript
function handleMessage(clientId, data) {
try {
const message = JSON.parse(data);
switch (message.type) {
case 'join':
handleJoinRoom(clientId, message.room);
break;
case 'leave':
handleLeaveRoom(clientId, message.room);
break;
case 'message':
handleRoomMessage(clientId, message);
break;
default:
console.warn(`Unknown message type: ${message.type}`);
}
} catch (error) {
console.error('Error handling message:', error);
}
}测试验证
bash
node test/messages.test.js预期输出
✅ Message handling tests passed第 5 课:实时聊天系统(20 分钟)
学习目标
- 实现完整的聊天系统
- 掌握在线用户管理
- 学习消息历史
课程内容
聊天系统
- 用户注册
- 在线用户
- 聊天消息
在线用户
- 用户状态
- 用户列表
- 状态同步
消息历史
- 消息存储
- 历史查询
- 消息分页
实践操作
javascript
class ChatServer {
constructor() {
this.users = new Map();
this.messages = [];
}
handleConnection(ws) {
const userId = generateUserId();
this.users.set(userId, { ws, id: userId });
// 通知其他用户
this.broadcastUserList();
return userId;
}
handleMessage(userId, message) {
const user = this.users.get(userId);
if (!user) return;
const chatMessage = {
id: generateMessageId(),
userId,
username: user.username,
content: message.content,
timestamp: Date.now()
};
this.messages.push(chatMessage);
this.broadcastMessage(chatMessage);
}
broadcastMessage(message) {
this.users.forEach((user) => {
if (user.ws.readyState === WebSocket.OPEN) {
user.ws.send(JSON.stringify({
type: 'message',
data: message
}));
}
});
}
}测试验证
bash
npm test预期输出
✅ Chat system tests passed第 6 课:性能优化(15 分钟)
学习目标
- 理解性能瓶颈
- 实现连接管理
- 学习消息压缩
课程内容
性能瓶颈
- 连接数限制
- 内存使用
- 消息延迟
连接管理
- 心跳检测
- 连接池
- 负载均衡
消息优化
- 消息压缩
- 批量发送
- 消息队列
实践操作
javascript
// 心跳检测
function startHeartbeat(ws, interval = 30000) {
const heartbeat = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.ping();
} else {
clearInterval(heartbeat);
}
}, interval);
ws.on('pong', () => {
// 心跳响应
});
}
// 消息压缩
function compressMessage(message) {
const zlib = require('zlib');
return zlib.deflateSync(JSON.stringify(message)).toString('base64');
}
function decompressMessage(compressed) {
const zlib = require('zlib');
const buffer = Buffer.from(compressed, 'base64');
return JSON.parse(zlib.inflateSync(buffer).toString());
}测试验证
bash
node test/performance.test.js预期输出
✅ Performance optimization tests passed第 7 课:安全实现(20 分钟)
学习目标
- 理解 WebSocket 安全
- 实现身份验证
- 学习消息加密
课程内容
安全措施
- 身份验证
- 权限控制
- 消息加密
身份验证
- JWT 验证
- 握手验证
- 会话管理
消息安全
- 消息验证
- 速率限制
- 防止注入
实践操作
javascript
// 身份验证中间件
function authMiddleware(ws, req) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
ws.close(1008, 'No token provided');
return false;
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
ws.userId = decoded.userId;
return true;
} catch (err) {
ws.close(1008, 'Invalid token');
return false;
}
}
// 消息验证
function validateMessage(message) {
if (!message.type || typeof message.type !== 'string') {
throw new Error('Invalid message type');
}
if (!message.content || typeof message.content !== 'string') {
throw new Error('Invalid message content');
}
if (message.content.length > 1000) {
throw new Error('Message too long');
}
}测试验证
bash
node test/security.test.js预期输出
✅ Security tests passed第 8 课:总结与扩展(15 分钟)
学习目标
- 回顾课程内容
- 总结核心概念
- 探索扩展方向
课程内容
课程回顾
- WebSocket 协议
- 房间管理
- 消息处理
- 性能优化
- 安全实现
核心概念总结
- 实时通信
- 全双工通信
- 消息广播
- 连接管理
扩展方向
- 消息持久化
- 私聊功能
- 文件传输
- 消息加密
- 消息撤回
实践操作
bash
# 运行所有测试
npm test
# 思考如何扩展功能
# 实现消息持久化、私聊等功能预期输出
✅ 所有测试通过学习成果
完成本课程后,你将能够:
- ✅ 理解 WebSocket 协议和实现
- ✅ 实现完整的实时聊天系统
- ✅ 掌握房间管理和消息广播
- ✅ 优化 WebSocket 性能
- ✅ 实现 WebSocket 安全
参考资源
下一步
完成本课程后,你可以继续学习:
- 微服务架构
- 容器化部署(Docker)
- CI/CD 持续集成
所有教学材料已保存。准备录制。

扫描二维码关注"架构师AI杜"公众号,获取更多技术内容和最新动态
