关于 websocket-implementation
用于设计可扩展 WebSocket 系统的技能,涵盖连接管理、消息路由和错误处理。面向构建实时通信的开发者,并提供水平扩展与实现模式的指导。
主要功能
- 01连接生命周期管理
- 02消息路由与错误处理
- 03支持水平扩展
- 04Node.js 和 Python 服务端指南
- 05浏览器客户端与协议指南
适用场景
- 01构建实时聊天
- 02发送实时通知
- 03创建协作编辑工具
- 04向客户端推送事件流
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ aj-geddes/ useful-ai-prompts --skill websocket-implementation安装后在 Claude Code 中输入/websocket-implementation确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/browser-websocket-client.mdmessage-types-and-protocols.mdnodejs-websocket-server-socketio.mdpython-websocket-server-aiohttp.mdscaling-with-redis.mdscripts/validate-api.shtemplates/api-scaffold.yaml详细介绍
WebSocket 实现
目录
概述
构建可扩展的 WebSocket 系统,实现实时通信,并提供妥善的连接管理、消息路由、错误处理和水平扩展支持。
适用场景
- 构建实时聊天和消息传递功能
- 实现实时通知
- 创建协作编辑工具
- 广播实时数据更新
- 构建实时仪表盘
- 向客户端流式传输事件
- 开发实时多人游戏
快速开始
最简可运行示例:
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const redis = require("redis");
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: { origin: "*" },
transports: ["websocket", "polling"],
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: 5,
});
// Redis adapter for horizontal scaling
const redisClient = redis.createClient();
const { createAdapter } = require("@socket.io/redis-adapter");
io.adapter(createAdapter(redisClient, redisClient.duplicate()));
// Connection management
const connectedUsers = new Map();
// ... (see reference guides for full implementation)
参考指南
references/ 目录中的详细实现:
| 指南 | 内容 |
|---|---|
| Node.js WebSocket Server (Socket.IO) | Node.js WebSocket 服务器(Socket.IO) |
| Browser WebSocket Client | 浏览器 WebSocket 客户端 |
| Python WebSocket Server (aiohttp) | Python WebSocket 服务器(aiohttp) |
| Message Types and Protocols | 消息类型和协议 |
| Scaling with Redis | 使用 Redis 进行扩展 |
最佳实践
✅ 应该
- 实施妥善的身份验证
- 平稳处理重新连接
- 有效管理房间/频道
- 适当地持久化消息
- 监控活动连接
- 实施在线状态功能
- 使用 Redis 进行扩展
- 添加消息确认机制
- 实施速率限制
- 妥善处理错误
❌ 不应该
- 发送未经加密的敏感数据
- 在内存中无限期保留消息历史
- 允许任意创建房间/频道
- 忘记清理已断开的连接
- 频繁发送大型消息
- 忽略网络故障
- 在消息中存储密码
- 跳过身份验证/授权
- 让连接数无限增长
- 从一开始就忽视可扩展性
评论
支持 Markdown