websocket-implementation · secondsky — Claude Code skill: real-time with Socket.IO
A skill that has your agent write the WebSocket server and client: rooms, reconnection, Redis scaling.
npx skills add secondsky/claude-skills --skill websocket-implementation -a claude-codeWhat websocket-implementation does
The skill hands your agent working templates for real-time messaging on Socket.IO. The server side covers token auth in the handshake, a map of connected users, rooms via socket.join, and broadcasts to a room or a single user. Helper functions handle targeted delivery: profile updates, room notifications, direct messages.
The client is a class with a message queue. If the socket is down, the message waits instead of disappearing, then goes out once the connection returns. Reconnection comes with a delay and an attempt limit. A React hook, useWebSocket, returns connection state, the message list and a send function. The hook pulls the token from your own getToken() helper, which you have to write — the skill ships no implementation for it.
Multiple servers need the @socket.io/redis-adapter wired to REDIS_URL. Skip Redis and horizontal scaling breaks: a message sent on one instance never reaches clients on another. The skill includes a table for picking an architecture by connection count, plus Express endpoints /api/ws/stats and /api/ws/health for monitoring. Python variants on aiohttp and FastAPI live in references/python-websocket.md.
What it helps with
- stand up a Socket.IO server with token authentication
- route messages to rooms and to individual users
- survive a dropped connection without losing queued messages
- spread connections across instances with Redis
- wire WebSocket into a React component with one hook
Example prompts for the agent
- Write a Socket.IO server with rooms and token auth from the handshake
- Build a useWebSocket React hook that queues messages while offline
- Add the Redis adapter so messages reach clients on other instances
How to install websocket-implementation
1Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill websocket-implementation -a claude-code2Manually: put the files in place
~/.claude/skills/websocket-implementation/SKILL.mdCopy the whole skill folder; for one project use .claude/skills/websocket-implementation/
1Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill websocket-implementation -a codex2Manually: put the files in place
.agents/skills/websocket-implementation/SKILL.mdFor all projects use ~/.agents/skills/
1Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill websocket-implementation -a cursor2Manually: put the files in place
.cursor/skills/websocket-implementation/SKILL.mdCursor also reads .agents/skills/ and .claude/skills/
1GitHub CLI
gh skill install secondsky/claude-skills websocket-implementation2Manually: put the files in place
.github/skills/websocket-implementation/SKILL.md1Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill websocket-implementation -a gemini-cli2Platform CLI
gemini skills install https://github.com/secondsky/claude-skills --path plugins/websocket-implementation/skills/websocket-implementationManually: put the files in place
.devin/skills/websocket-implementation/SKILL.mdThe legacy .windsurf/skills/ path still works
Skills CLI (Vercel)
npx skills add secondsky/claude-skills --skill websocket-implementation -a opencodeClaude.ai
Zip the folder and upload it in Settings → Capabilities → Skills
Step by step, with commands for each platform: How to install skills in Claude Code: five ways
Questions about websocket-implementation
How do I install websocket-implementation in Claude?
Run npx skills add secondsky/claude-skills --skill websocket-implementation -a claude-code. The skill file then sits at ~/.claude/skills/websocket-implementation/SKILL.md.
What does websocket-implementation do?
It gives your agent Socket.IO server and client templates: connection management, rooms, a message queue, reconnection, and a Redis adapter for multiple instances.
Do I need Redis for this skill?
Not for a single server. Redis matters once you run several instances — without @socket.io/redis-adapter, messages do not travel between them.
Source text
SKILL.md · MIT
---
name: websocket-implementation
description: Implements real-time WebSocket communication with connection management, room-based messaging, and horizontal scaling. Use when building chat systems, live notifications, collaborative tools, or real-time dashboards.
license: MIT
---
# WebSocket Implementation
Build scalable real-time communication systems with proper connection management.
## Server Implementation (Socket.IO)
```javascript
const { Server } = require('socket.io');
const { createAdapter } = require('@socket.io/redis-adapter');
const { createClient } = require('redis');
const io = new Server(server, {
cors: { origin: process.env.CLIENT_URL, credentials: true }
});
// Redis adapter for horizontal scaling
const pubClient = createClient({ url: process.env.REDIS_URL });
const subClient = pubClient.duplicate();
Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
io.adapter(createAdapter(pubClient, subClient));
});
// Connection management
const users = new Map();
io.use((socket, next) => {
const token = socket.handshake.auth.token;
try {
socket.user = verifyToken(token);
next();
} catch (err) {
next(new Error('Authentication failed'));
}
});
io.on('connection', (socket) => {
users.set(socket.user.id, socket.id);
console.log(`User ${socket.user.id} connected`);
socket.on('join-room', (roomId) => {
socket.join(roomId);
socket.to(roomId).emit('user-joined', socket.user);
});
socket.on('message', ({ roomId, content }) => {
io.to(roomId).emit('message', {
userId: socket.user.id,
content,
timestamp: Date.now()
});
});
socket.on('disconnect', () => {
users.delete(socket.user.id);
});
});
// Utility methods for message distribution
function broadcastUserUpdate(userId, data) {
io.to(`user:${userId}`).emit('user-update', data);
}
function notifyRoom(roomId, event, data) {
io.to(`room:${roomId}`).emit(event, data);
}
function sendDirectMessage(userId, message) {
const socketId = users.get(userId);
if (socketId) {
io.to(socketId).emit('direct-message', message);
}
}
```
## Client Implementation
```javascript
import { io } from 'socket.io-client';
class WebSocketClient {
constructor(url, token) {
this.socket = io(url, {
auth: { token },
reconnection: true,
reconnectionDelay: 1000,
reconnectionAttempts: 5
});
this.messageQueue = [];
this.setupListeners();
}
setupListeners() {
this.socket.on('connect', () => {
console.log('Connected');
this.flushQueue();
});
this.socket.on('disconnect', (reason) => {
console.log('Disconnected:', reason);
});
this.socket.on('message', (msg) => {
this.onMessage?.(msg);
});
}
joinRoom(roomId) {
this.socket.emit('join-room', roomId);
}
send(roomId, content) {
if (this.socket.connected) {
this.socket.emit('message', { roomId, content });
} else {
this.messageQueue.push({ roomId, content });
}
}
flushQueue() {
while (this.messageQueue.length > 0) {
const msg = this.messageQueue.shift();
this.socket.emit('message', msg);
}
}
}
```
## React Hook
```javascript
function useWebSocket(url) {
const [socket, setSocket] = useState(null);
const [connected, setConnected] = useState(false);
const [messages, setMessages] = useState([]);
useEffect(() => {
// getToken() is a user-supplied helper that returns the current auth token
// Example implementations:
// - From localStorage: () => localStorage.getItem('authToken')
// - From context: () => authContext.token
// - From cookie: () => document.cookie.split('token=')[1]
const ws = io(url, { auth: { token: getToken() } });
ws.on('connect', () => setConnected(true));
ws.on('disconnect', () => setConnected(false));
ws.on('message', (msg) => {
setMessages(prev => [...prev, msg]);
});
setSocket(ws);
return () => ws.disconnect();
}, [url]);
const send = useCallback((roomId, content) => {
socket?.emit('message', { roomId, content });
}, [socket]);
return { connected, messages, send };
}
```
## Message Protocol
```typescript
interface Message {
type: 'message' | 'typing' | 'presence';
roomId: string;
userId: string;
content?: string;
timestamp: number;
}
// Acknowledge delivery
socket.emit('message', data, (ack) => {
if (ack.success) console.log('Delivered');
});
```
## Additional Implementations
See [references/python-websocket.md](references/python-websocket.md) for:
- Python aiohttp WebSocket server
- FastAPI WebSocket endpoints
- Async connection handling
## Scaling Considerations
| Connections | Architecture |
|-------------|--------------|
| <10K | Single server |
| 10K-100K | Redis pub/sub |
| >100K | Sharded Redis + load balancer |
## Monitoring Endpoints
```javascript
// Express endpoints for operational visibility
app.get('/api/ws/stats', (req, res) => {
res.json({
activeConnections: io.sockets.sockets.size,
rooms: [...io.sockets.adapter.rooms.keys()],
users: users.size
});
});
app.get('/api/ws/health', (req, res) => {
res.json({
status: 'healthy',
uptime: process.uptime(),
memoryUsage: process.memoryUsage()
});
});
```
## Best Practices
- Authenticate before allowing operations
- Implement reconnection with exponential backoff
- Use rooms and channels for targeted broadcasting
- Add heartbeat/ping for connection health
- Persist important messages to database
- Monitor active connection counts
- Display user presence/availability status
- Implement rate limiting on incoming messages
- Use acknowledgments to confirm message delivery
- Leverage Redis for distributed deployments
- Implement comprehensive error handling
## Never Do
- Send sensitive data unencrypted
- Store unlimited messages in memory
- Skip authorization on room joins
- Ignore connection error handling
- Allow unbounded room subscriptions
- Neglect cleanup of disconnected user data
- Send frequent oversized message payloads
- Include authentication credentials in message bodies
- Deploy without security validation
- Allow uncontrolled connection accumulation
- Build without scalability consideration
© secondsky · MIT · secondsky/claude-skills
Similar skills
Everything for Backend and APIs →websocket-implementation by other authors comes first.