websocket-engineer
БесплатноЗапускает вложенные скриптыНе проверенExpert WebSocket and real-time communication engineering — WebSocket protocol (RFC 6455), ws/Socket.IO server implementation, authentication…
от oimiragieo★ 48 звёзд на GitHubОб этом скилле
WebSocket Engineer Skill
Overview
Real-time, bidirectional communication systems using WebSockets and related protocols. Covers protocol fundamentals, server implementation, authentication, scaling, fault tolerance, and browser client patterns.
Protocol Fundamentals
HTTP Upgrade → WebSocket Handshake
GET /ws HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: <base64 random>
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: <SHA-1 of key + GUID>
After handshake: full-duplex binary framing
Frame types: text (0x1), binary (0x2), close (0x8), ping (0x9), pong (0xA)
Server Implementation — ws (Node.js)
const { WebSocketServer, WebSocket } = require('ws');
const http = require('http');
const server = http.createServer(app);
const wss = new WebSocketServer({ server, path: '/ws' });
// Connection map for targeted sends
const clients = new Map(); // userId → Set<WebSocket>
wss.on('connection', (ws, req) => {
// 1. Authenticate immediately
const token = extractToken(req);
const user = verifyToken(token);
if (!user) {
ws.close(4001, 'Unauthorized');
return;
}
// 2. Register client
if (!clients.has(user.id)) clients.set(user.id, new Set());
clients.get(user.id).add(ws);
ws.userId = user.id;
// 3. Heartbeat setup
ws.isAlive = true;
ws.on('pong', () => {
ws.isAlive = true;
});
// 4. Message handling
ws.on('message', (data, isBinary) => {
try {
const msg = isBinary ? data : JSON.parse(data.toString());
handleMessage(ws, msg);
} catch (err) {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid message' }));
}
});
// 5. Cleanup on close
ws.on('close', (code, reason) => {
clients.get(ws.userId)?.delete(ws);
if (clients.get(ws.userId)?.size === 0) clients.delete(ws.userId);
console.log(`Client ${ws.userId} disconnected: ${code} ${reason}`);
});
ws.on('error', err => {
console.error(`WebSocket error for ${ws.userId}:`, err.message);
});
// 6. Send initial state
ws.send(JSON.stringify({ type: 'connected', userId: user.id }));
});
// Heartbeat interval — terminate dead connections every 30s
const heartbeat = setInterval(() => {
wss.clients.forEach(ws => {
if (!ws.isAlive) {
ws.terminate();
return;
}
ws.isAlive = false;
ws.ping();
});
}, 30_000);
wss.on('close', () => clearInterval(heartbeat));
// Targeted send to specific user (all connections)
function sendToUser(userId, payload) {
const userClients = clients.get(userId);
if (!userClients) return;
const data = JSON.stringify(payload);
userClients.forEach(ws => {
if (ws.readyState === WebSocket.OPEN) ws.send(data);
});
}
// Broadcast to all connected clients
function broadcast(payload, excludeUserId = null) {
const data = JSON.stringify(payload);
wss.clients.forEach(ws => {
if (ws.readyState === WebSocket.OPEN && ws.userId !== excludeUserId) {
ws.send(data);
}
});
}
Authentication Patterns
// Token in query string (simple, TLS required)
wss.on('connection', (ws, req) => {
const url = new URL(req.url, 'http://localhost');
const token = url.searchParams.get('token');
// ...
});
// Cookie-based (preferred for browsers)
wss.on('connection', (ws, req) => {
const cookies = parseCookies(req.headers.cookie);
const sessionId = cookies['session'];
// ...
});
// Custom header via Sec-WebSocket-Protocol (workaround for headers limitation)
// Browser: new WebSocket(url, ['v1', token])
// Server: req.headers['sec-websocket-protocol']
// First message auth (for frameworks that don't support upgrade auth)
ws.once('message', data => {
const { type, token } = JSON.parse(data);
if (type !== 'auth') {
ws.close(4001, 'Auth required');
return;
}
const user = verifyToken(token);
if (!user) {
ws.close(4001, 'Unauthorized');
return;
}
ws.userId = user.id;
setupMessageHandler(ws);
});
Horizontal Scaling with Redis
const { createClient } = require('redis');
const { WebSocketServer } = require('ws');
const pub = createClient({ url: process.env.REDIS_URL });
const sub = createClient({ url: process.env.REDIS_URL });
await pub.connect();
await sub.connect();
const CHANNEL = 'ws:broadcast';
// Subscribe to Redis messages and relay to local clients
await sub.subscribe(CHANNEL, message => {
const payload = JSON.parse(message);
// Deliver to local connections matching the target
wss.clients.forEach(ws => {
if (ws.readyState === WebSocket.OPEN) {
if (!payload.targetUserId || ws.userId === payload.targetUserId) {
ws.send(JSON.stringify(payload.data));
}
}
});
});
// Publish cross-instance — all servers receive and relay
async function broadcastViaRedis(data, targetUserId = null) {
await pub.publish(
CHANNEL,
JSON.stringify({ data, targetUserId, serverId: process.en
Установить websocket-engineer в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
BashReadWriteEditВложенные файлы
FAQ
Что делает скилл websocket-engineer?
Expert WebSocket and real-time communication engineering — WebSocket protocol (RFC 6455), ws/Socket.IO server implementation, authentication, heartbeat/reconnection, horizontal scaling with Redis pub/sub, Server-Sent Events (SSE), WebRTC signaling, and observability. Use for chat, live dashboards, multiplayer, collaborative editing, and event-driven real-time systems.
Как установить скилл websocket-engineer?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл websocket-engineer запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic