Langsung ke konten
Skillpedia
API & server (backend)12k Β· #11469

websocket-engineer

Fungsinya

Skill ini memandu AI untuk membangun koneksi dua arah yang langsung, dengan room, autentikasi, dan penskalaan. Skill ini untuk pengembang yang membutuhkan pembaruan instan.

Kapan dipakai

  • βœ“Saat Anda membangun fitur chat langsung atau notifikasi real-time.
  • βœ“Saat Anda perlu menskalakan server WebSocket di beberapa mesin dengan Redis.
  • βœ“Saat Anda ingin melacak pengguna yang sedang online dan mengelola room.

Link skill

https://github.com/Jeffallan/claude-skills/blob/main/skills/websocket-engineer/SKILL.md

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/Jeffallan/claude-skills/blob/main/skills/websocket-engineer/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit β†’

Contoh permintaan ke AI

β€œBisakah Anda membantu saya menambahkan room chat langsung dengan Socket.IO dan pemeriksaan login pengguna?”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

AI merencanakan desain koneksi, membangun server, menguji koneksi, lalu mengatur penskalaan dan pemantauan.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari GitHub.

WebSocket Engineer

Core Workflow

  1. Analyze requirements β€” Identify connection scale, message volume, latency needs
  2. Design architecture β€” Plan clustering, pub/sub, state management, failover
  3. Implement β€” Build WebSocket server with authentication, rooms, events
  4. Validate locally β€” Test connection handling, auth, and room behavior before scaling (e.g., npx wscat -c ws://localhost:3000); confirm auth rejection on missing/invalid tokens, room join/leave events, and message delivery
  5. Scale β€” Verify Redis connection and pub/sub round-trip before enabling the adapter; configure sticky sessions and confirm with test connections across multiple instances; set up load balancing
  6. Monitor β€” Track connections, latency, throughput, error rates; add alerts for connection-count spikes and error-rate thresholds

Reference Guide

Load detailed guidance based on context:

Topic Reference Load When
Protocol references/protocol.md WebSocket handshake, frames, ping/pong, close codes
Scaling references/scaling.md Horizontal scaling, Redis pub/sub, sticky sessions
Patterns references/patterns.md Rooms, namespaces, broadcasting, acknowledgments
Security references/security.md Authentication, authorization, rate limiting, CORS
Alternatives references/alternatives.md SSE, long polling, when to choose WebSockets

Code Examples

Server Setup (Socket.IO with Auth and Room Management)

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,
});

// Authentication middleware β€” runs before connection is established
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 for horizontal scaling
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})`);

  // Presence: mark user online
  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);

Client-Side Reconnection with Exponential Backoff

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

const socket = io("wss://api.example.com", {
  auth: { token: getAuthToken() },
  reconnection: true,
  reconnectionAttempts: 10,
  reconnectionDelay: 1000,       // initial delay (ms)
  reconnectionDelayMax: 30000,   // cap at 30 s
  randomizationFactor: 0.5,      // jitter to avoid thundering herd
});

// Queue messages while disconnected
let messageQueue = [];

socket.on("connect", () => {
  console.log("connected:", socket.id);
  // Flush queued messages
  messageQueue.forEach((msg) => socket.emit("message", msg));
  messageQueue = [];
});

socket.on("disconnect", (reason) => {
  console.warn("disconnected:", reason);
  if (reason === "io server disconnect") socket.connect(); // manual reconnect
});

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); // buffer until reconnected
  }
}

Constraints

MUST DO

  • Use sticky sessions for load balancing (WebSocket connections are stateful β€” requests must route to the same server instance)
  • Implement heartbeat/ping-pong to detect dead connections (TCP keepalive alone i
Pertanyaan umum

Apakah skill ini hanya mencakup Socket.IO?

Tidak. Skill ini mencakup WebSocket dan Socket.IO, serta menyebutkan beberapa alternatif.

Bagaimana penskalaan di banyak server?

Skill ini memakai Redis pub/sub dan sticky session agar pesan sampai ke pengguna yang terhubung ke server mana pun.

Apakah keamanan juga dicakup?

Ya, skill ini mencakup autentikasi, otorisasi, pembatasan laju, dan CORS.

Detail

Deskripsi asli dari pembuat

Use when building real-time communication systems with WebSockets or Socket.IO. Invoke for bidirectional messaging, horizontal scaling with Redis, presence tracking, room management.

repo: Jeffallan/claude-skills

Popularitas

Bintang GitHub
12k
Peringkat
#11469
Lisensi
MIT
Diperbarui
30/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa