jpskill.com
🛠️ 開発・MCP コミュニティ

websocket-builder

WebSocketを使ったリアルタイム機能(ライブアップデート、チャット、データストリーミングなど)を構築したい場合に、サーバー設定、認証、再接続処理、Redisを使った拡張までを支援するSkill。

📜 元の英語説明(参考)

When the user wants to build real-time features using WebSockets. Use when the user mentions "WebSocket," "real-time," "live updates," "socket," "ws," "push notifications," "live chat," "streaming data," or "bidirectional communication." Covers server setup, room management, authentication, reconnection handling, and scaling with Redis pub/sub. For data persistence, see realtime-database.

🇯🇵 日本人クリエイター向け解説

一言でいうと

WebSocketを使ったリアルタイム機能(ライブアップデート、チャット、データストリーミングなど)を構築したい場合に、サーバー設定、認証、再接続処理、Redisを使った拡張までを支援するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o websocket-builder.zip https://jpskill.com/download/15562.zip && unzip -o websocket-builder.zip && rm websocket-builder.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15562.zip -OutFile "$d\websocket-builder.zip"; Expand-Archive "$d\websocket-builder.zip" -DestinationPath $d -Force; ri "$d\websocket-builder.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して websocket-builder.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → websocket-builder フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

WebSocketビルダー

概要

チャット、ライブダッシュボード、共同編集、通知など、リアルタイム機能に対応した、本番環境で使用できるWebSocketサーバーを構築します。ハンドシェイク時の認証、ルーム/チャンネル管理、接続ライフサイクル、自動再接続、メッセージの順序付け、Redis pub/subによる水平スケーリングといった、難しい部分を処理します。

手順

1. サーバーのセットアップ

WebSocketサーバーをセットアップする際は、以下を行ってください。

  • 既存のHTTPサーバーにアタッチする(ポートを共有する)
  • 成熟したライブラリを使用する:Node.jsの場合はws、Pythonの場合はwebsockets、Goの場合はgorilla/websocket
  • ping/pongハートビートを実装する(30秒間隔、90秒タイムアウト)
  • 悪用を防ぐために、最大メッセージサイズを設定する(デフォルト:64KB)
  • ユーザーごとの接続制限を追加する(デフォルト:同時接続数5)

2. 認証

WebSocketハンドシェイク中に認証を行い、後から認証を行わないでください。

1. クライアントはクエリ文字列にトークンを含めて接続します: ws://host/ws?token=<jwt>
2. サーバーは接続をアップグレードする前にJWTを検証します
3. 無効な場合 → アップグレードが完了する前に401で拒否します
4. 後で使用するために、ユーザーコンテキストをソケットオブジェクトにアタッチします

接続後のメッセージによる認証は受け入れないでください。接続はすでに開いており、リソースが割り当てられています。

3. ルーム/チャンネル管理

RoomManager:
  join(socketId, roomId) — ソケットをルームに追加し、メンバーに通知します
  leave(socketId, roomId) — ソケットを削除し、メンバーに通知します
  broadcast(roomId, event, data, excludeSocketId?) — ルーム内の全員に送信します
  getMembers(roomId) — 接続されているユーザーIDのリストを取得します
  getUserRooms(socketId) — ソケットのルームのリストを取得します

接続時:データベースからユーザーのチャンネルルームに自動的に参加します
切断時:すべてのルームから退出、プレゼンスアップデートをブロードキャストします

4. イベントルーティング

イベントタイプを含むメッセージ形式を使用します。

{ "event": "message.send", "data": { "channelId": "ch_1", "content": "Hello" }, "id": "client-uuid" }

イベントをハンドラーにルーティングします。

eventHandlers = {
  "message.send": handleMessageSend,
  "message.edit": handleMessageEdit,
  "typing.start": handleTypingStart,
  "presence.heartbeat": handleHeartbeat
}

べき等性と確認応答のために、クライアントが生成したidを常に含めてください。

5. Redis Pub/Subによるスケーリング

マルチサーバーデプロイメントの場合:

1. 各サーバーは、ルームIDに一致するRedisチャンネルをサブスクライブします
2. ブロードキャスト時:ローカルのみのブロードキャストの代わりに、Redisチャンネルに公開します
3. 各サーバーは公開を受信し、そのルーム内のローカルソケットに転送します
4. Redisアダプターを使用します(例:@socket.io/redis-adapter または ioredis を使用したカスタム)

6. 再接続プロトコル

クライアント側:
  1. 切断時:指数バックオフで再接続を試みます(1秒、2秒、4秒、最大30秒)
  2. 再接続時:last_event_idをサーバーに送信します
  3. サーバーはそのID以降の未処理のイベントを再生します
  4. クライアントはローカル状態とマージし、イベントIDで重複排除します

サーバー側:
  1. 最近のイベントをRedisソート済みセットに保持します(TTL:1時間)
  2. last_event_idで再接続時:そのID以降のすべてのイベントを返します
  3. IDが古すぎる場合(保持期間を超える場合):完全な状態の更新を送信します

例1:チャットWebSocketサーバー(Node.js)

プロンプト: 「ルームとJWT認証を備えたExpressアプリ用のWebSocketサーバーをセットアップしてください」

出力: 認証された接続、ルームマネージャー、イベントルーティング、ping/pongハートビート、および再接続サポートを備えたサーバー。ファイル:ws/server.tsws/rooms.tsws/handlers/ws/middleware/auth.ts

例2:ライブダッシュボード(Python)

プロンプト: 「監視ダッシュボードのリアルタイムアップデートが必要です。FastAPIバックエンド、500人の同時視聴者。」

出力: ブロードキャスト専用チャンネル(視聴者は送信しない)、水平スケーリング用のRedis pub/sub、接続プーリング、および自動クリーンアップを備えたWebSocketエンドポイント。ファイル:realtime/server.pyrealtime/broadcaster.pyrealtime/redis_pubsub.py

ガイドライン

  • 常にハンドシェイク時に認証する — 接続が開いた後は絶対に認証しない
  • 大量のペイロード(画像、ファイル)にはバイナリフレームを使用する — JSONにはテキストフレームを使用する
  • バックプレッシャーを実装する — クライアントが追いつけない場合は、バッファリングしてから切断する
  • 接続ライフサイクルをログに記録する — 接続、切断、エラー、ルームへの参加/退出(これがないとデバッグは困難です)
  • 接続の切断でテストする — メッセージの途中で接続を強制終了して、復旧を確認する
  • アイドルタイムアウトを設定する — ハートビートの送信を停止したクライアントを切断する
  • クライアント入力を決して信頼しない — すべてのメッセージを予期されるスキーマに対して検証する
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

WebSocket Builder

Overview

Builds production-ready WebSocket servers for real-time features — chat, live dashboards, collaborative editing, notifications. Handles the hard parts: authentication during handshake, room/channel management, connection lifecycle, automatic reconnection, message ordering, and horizontal scaling via Redis pub/sub.

Instructions

1. Server Setup

When setting up a WebSocket server:

  • Attach to existing HTTP server (share the port)
  • Use a mature library: ws for Node.js, websockets for Python, gorilla/websocket for Go
  • Implement ping/pong heartbeats (30s interval, 90s timeout)
  • Set max message size to prevent abuse (default: 64KB)
  • Add connection limits per user (default: 5 concurrent connections)

2. Authentication

Authenticate during the WebSocket handshake, not after:

1. Client connects with token in query string: ws://host/ws?token=<jwt>
2. Server validates JWT before upgrading the connection
3. If invalid → reject with 401 before upgrade completes
4. Attach user context to the socket object for later use

Do NOT accept auth via a post-connection message — the connection is already open and resources allocated.

3. Room/Channel Management

RoomManager:
  join(socketId, roomId) — Add socket to room, notify members
  leave(socketId, roomId) — Remove socket, notify members
  broadcast(roomId, event, data, excludeSocketId?) — Send to all in room
  getMembers(roomId) — List connected user IDs
  getUserRooms(socketId) — List rooms for a socket

On connect: auto-join user's channel rooms from database
On disconnect: leave all rooms, broadcast presence update

4. Event Routing

Use a message format with event types:

{ "event": "message.send", "data": { "channelId": "ch_1", "content": "Hello" }, "id": "client-uuid" }

Route events to handlers:

eventHandlers = {
  "message.send": handleMessageSend,
  "message.edit": handleMessageEdit,
  "typing.start": handleTypingStart,
  "presence.heartbeat": handleHeartbeat
}

Always include a client-generated id for idempotency and acknowledgment.

5. Scaling with Redis Pub/Sub

For multi-server deployments:

1. Each server subscribes to Redis channels matching room IDs
2. On broadcast: publish to Redis channel instead of local-only broadcast
3. Each server receives the publish and forwards to local sockets in that room
4. Use Redis adapter (e.g., @socket.io/redis-adapter or custom with ioredis)

6. Reconnection Protocol

Client-side:
  1. On disconnect: attempt reconnect with exponential backoff (1s, 2s, 4s, max 30s)
  2. On reconnect: send last_event_id to server
  3. Server replays missed events since that ID
  4. Client merges with local state, deduplicating by event ID

Server-side:
  1. Keep recent events in Redis sorted set (TTL: 1 hour)
  2. On reconnect with last_event_id: return all events after that ID
  3. If ID is too old (beyond retention): send full state refresh

Examples

Example 1: Chat WebSocket Server (Node.js)

Prompt: "Set up a WebSocket server for my Express app with rooms and JWT auth"

Output: Server with authenticated connections, room manager, event routing, ping/pong heartbeats, and reconnection support. Files: ws/server.ts, ws/rooms.ts, ws/handlers/, ws/middleware/auth.ts.

Example 2: Live Dashboard (Python)

Prompt: "I need real-time updates for a monitoring dashboard. FastAPI backend, 500 concurrent viewers."

Output: WebSocket endpoint with broadcast-only channels (viewers don't send), Redis pub/sub for horizontal scaling, connection pooling, and automatic cleanup. Files: realtime/server.py, realtime/broadcaster.py, realtime/redis_pubsub.py.

Guidelines

  • Always authenticate at handshake — never after connection is open
  • Use binary frames for large payloads (images, files) — text frames for JSON
  • Implement backpressure — if a client can't keep up, buffer then disconnect
  • Log connection lifecycle — connect, disconnect, error, room join/leave (debugging is hard without this)
  • Test with connection drops — kill connections mid-message to verify recovery
  • Set idle timeouts — disconnect clients that stop sending heartbeats
  • Never trust client input — validate every message against expected schema