AGENT SKILL

websocket-engineer

当使用 WebSocket 或 Socket.IO 构建实时通信系统时使用。适用于双向消息通信、Redis 水平扩展、在线状态追踪、房间管理。

License 许可
MIT
最近更新
2026-06-29
Stars
★ 0
Forks
0

01 前言 Front Matter

name
websocket-engineer
license
MIT
metadata
{ "role": "specialist", "scope": "implementation", "author": "https://github.com/Jeffallan", "domain": "api-architecture", "version": "1.1.0", "triggers": "WebSocket, Socket.IO, real-time communication, bidirectional messaging, pub/sub, server push, live updates, chat systems, presence tracking", "output-format": "code", "related-skills": "fastapi-expert, nestjs-expert, devops-engineer, monitoring-expert, security-reviewer" }
description
当使用 WebSocket 或 Socket.IO 构建实时通信系统时使用。适用于双向消息通信、Redis 水平扩展、在线状态追踪、房间管理。

02 资源文件 61

03 SKILL.md 正文

WebSocket 工程师

核心工作流程

  1. 分析需求 — 确定连接规模、消息量、延迟需求
  2. 设计架构 — 规划集群、pub/sub、状态管理、故障转移
  3. 实现 — 构建带认证、房间、事件的 WebSocket 服务器
  4. 本地验证 — 在扩展前测试连接处理、认证和房间行为(例如 npx wscat -c ws://localhost:3000);确认缺少/无效 token 时的认证拒绝、房间加入/离开事件以及消息投递
  5. 扩展 — 在启用 adapter 前验证 Redis 连接和 pub/sub 往返;配置 sticky sessions 并通过跨多个实例的测试连接确认;设置负载均衡
  6. 监控 — 追踪连接数、延迟、吞吐量、错误率;为连接数峰值和错误率阈值添加告警

参考指南

根据上下文加载详细指导:

主题 参考文件 何时加载
协议 references/protocol.md WebSocket 握手、帧、ping/pong、关闭码
扩展 references/scaling.md 水平扩展、Redis pub/sub、sticky sessions
模式 references/patterns.md 房间、命名空间、广播、确认机制
安全 references/security.md 认证、授权、速率限制、CORS
替代方案 references/alternatives.md SSE、长轮询、何时选择 WebSocket

代码示例

服务端设置(带认证和房间管理的 Socket.IO)

import { createServer } from "http";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-adapter";
import { createClient } from "redis";
import jwt from "jsonwebtoken";

const httpServer = createServer();
const io = new Server(httpServer, {
  cors: { origin: process.env.ALLOWED_ORIGIN, credentials: true },
  pingTimeout: 20000,
  pingInterval: 25000,
});

// 认证中间件 — 在建立连接前执行
io.use((socket, next) => {
  const token = socket.handshake.auth.token;
  if (!token) return next(new Error("Authentication required"));
  try {
    socket.data.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    next(new Error("Invalid token"));
  }
});

// 用于水平扩展的 Redis adapter
const pubClient = createClient({ url: process.env.REDIS_URL });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);
io.adapter(createAdapter(pubClient, subClient));

io.on("connection", (socket) => {
  const { userId } = socket.data.user;
  console.log(`connected: ${userId} (${socket.id})`);

  // 在线状态:标记用户在线
  pubClient.hSet("presence", userId, socket.id);

  socket.on("join-room", (roomId) => {
    socket.join(roomId);
    socket.to(roomId).emit("user-joined", { userId });
  });

  socket.on("message", ({ roomId, text }) => {
    io.to(roomId).emit("message", { userId, text, ts: Date.now() });
  });

  socket.on("disconnect", () => {
    pubClient.hDel("presence", userId);
    console.log(`disconnected: ${userId}`);
  });
});

httpServer.listen(3000);

客户端重连(指数退避)

import { io } from "socket.io-client";

const socket = io("wss://api.example.com", {
  auth: { token: getAuthToken() },
  reconnection: true,
  reconnectionAttempts: 10,
  reconnectionDelay: 1000,       // 初始延迟(毫秒)
  reconnectionDelayMax: 30000,   // 上限 30 秒
  randomizationFactor: 0.5,      // 抖动避免惊群效应
});

// 断线时排队消息
let messageQueue = [];

socket.on("connect", () => {
  console.log("connected:", socket.id);
  // 发送队列中的消息
  messageQueue.forEach((msg) => socket.emit("message", msg));
  messageQueue = [];
});

socket.on("disconnect", (reason) => {
  console.warn("disconnected:", reason);
  if (reason === "io server disconnect") socket.connect(); // 手动重连
});

socket.on("connect_error", (err) => {
  console.error("connection error:", err.message);
});

function sendMessage(roomId, text) {
  const msg = { roomId, text };
  if (socket.connected) {
    socket.emit("message", msg);
  } else {
    messageQueue.push(msg); // 缓存直到重连
  }
}

约束条件

必须执行

  • 使用 sticky sessions 进行负载均衡(WebSocket 连接是有状态的 — 请求必须路由到同一服务器实例)
  • 实现心跳/ping-pong 以检测死连接(仅靠 TCP keepalive 不够)
  • 使用房间/命名空间进行消息范围控制,而非在应用逻辑中过滤
  • 在断线窗口期间对消息进行排队,避免静默丢数据
  • 在水平扩展前规划每个实例的连接限制

禁止执行

  • 在没有集群策略的情况下在内存中存储大量状态(应使用 Redis 或外部存储)
  • 未做显式升级处理就在同一端口混用 WebSocket 和 HTTP
  • 忘记处理连接清理(在线状态记录、房间成员、进行中的定时器)
  • 在生产前跳过负载测试 — 连接数峰值的行为与 HTTP 流量峰值不同

输出模板

实现 WebSocket 功能时,提供:

  1. 服务端设置(Socket.IO/ws 配置)
  2. 事件处理器(connection、message、disconnect)
  3. 客户端库(连接、事件、重连)
  4. 扩展策略的简要说明

知识参考

Socket.IO、ws、uWebSockets.js、Redis adapter、sticky sessions、nginx WebSocket 代理、JWT over WebSocket、房间/命名空间、确认机制、二进制数据、压缩、心跳、背压、水平 Pod 自动扩展

04 同仓库更多 Skills

Blake-John
Blake-John/agent-config

security-reviewer

识别安全漏洞,生成带有严重性评级的结构化审计报告,并提供可操作的安全修复建议。在开展安全审计、审查代码漏洞或分析基础设施安全时使用。适用于 SAST 扫描、渗透测试、DevSecOps 实践、云安全审查、依赖审计、密钥扫描或合规检查。生成漏洞报告、优先级建议和合规清单。

开发工程师测试与质量Skill与智能体开发
★ 0
Blake-John
Blake-John/agent-config

secure-code-guardian

用于实现认证/授权、保护用户输入或防御 OWASP Top 10 漏洞 —— 包括自定义安全实现,例如使用 bcrypt/argon2 哈希密码、使用参数化语句清理 SQL 查询、配置 CORS/CSP 头部、使用 Zod 验证输入以及设置 JWT token。适用于认证、授权、输入验证、加密、OWASP Top 10 防护、安全会话管理和安全加固。对于预构建的 OAuth/SSO 集成或独立的安全审计,请考虑使用更专业的 skill。

开发工程师
★ 0
Blake-John
Blake-John/agent-config

rust-engineer

编写、审查和调试符合 Rust 风格的代码,确保内存安全和零成本抽象。实现所有权模式、管理生命周期、设计 trait 层级、使用 tokio 构建异步应用程序,以及使用 Result/Option 结构化错误处理。适用于构建 Rust 应用程序、解决所有权或借用问题、设计基于 trait 的 API、实现 async/await 并发、创建 FFI 绑定,或优化性能和内存安全。触发词:Rust, Cargo, ownership, borrowing, lifetimes, async Rust, tokio, zero-cost abstractions, memory safety, systems programming。

开发工程师
★ 0
Blake-John
Blake-John/agent-config

react-native-expert

使用 React Native 和 Expo 构建、优化和调试跨平台移动应用。实现导航层级结构(标签页、堆栈、抽屉),配置原生模块,使用 memo 和 useCallback 优化 FlatList 渲染,处理 iOS 和 Android 的平台特定代码。在构建 React Native 或 Expo 移动应用、设置导航、集成原生模块、改善滚动性能、处理 SafeArea 或键盘输入、配置 Expo SDK 项目时使用。

前端开发
★ 0
Blake-John
Blake-John/agent-config

react-expert

当你使用 .jsx 或 .tsx 文件构建 React 18+ 应用、Next.js App Router 项目或 create-react-app 时使用。创建组件、实现自定义 hooks、调试渲染问题、将类组件迁移为函数组件、以及实现状态管理。适用于 Server Components、Suspense 边界、useActionState 表单、性能优化或 React 19 特性。

前端开发
★ 0
Blake-John
Blake-John/agent-config

python-pro

Use when building Python 3.11+ applications requiring type safety, async programming, or robust error handling. Generates type-annotated Python code, configures mypy in strict mode, writes pytest test suites with fixtures and mocking, and validates code with black and ruff. Invoke for type hints, async/await patterns, dataclasses, dependency injection, logging configuration, and structured error handling.

开发工程师
★ 0