Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计提醒

websocket-management网络套接字管理

Agent Skill

websocket-management 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

593

周安装

24

GitHub Stars

777

下载量

186
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:websocket-management(网络套接字管理)
来源仓库:https://github.com/dadbodgeoff/drift
仓库路径:skills/websocket-management
安装命令:
npx skills add https://github.com/dadbodgeoff/drift --skill websocket-management
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dadbodgeoff/drift --skill websocket-management

简介

用于管理 WebSocket 连接及相关协作流程。

  • 适合处理 GitHub 仓库状态和代码变更信息。
  • 支持 Issue、Pull Request 等协作事项的整理。
  • 通过 GitHub 仓库安装并使用 npx 命令添加。
  • 需评估是否会触发文件读写或外部命令执行。websocket-management 属于开发类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

WebSocket Connection Management

Production-grade WebSocket connection manager with health verification and capacity management.

When to Use This Skill

  • Building real-time features with WebSockets
  • Need connection limits (global and per-room)
  • Want to detect and clean up stale connections
  • Require reliable user-to-connection mapping

Core Concepts

WebSocket connections can appear connected but be stale (client crashed, network dropped). The solution:

  • Track connections by lobby/room AND by user ID
  • Enforce connection limits (global + per-lobby)
  • Ping/pong health verification
  • Automatic stale connection cleanup

Implementation

Python (FastAPI)

import asyncio
import json
import time
import logging
from typing import Dict, Optional, Set, Tuple
from fastapi import WebSocket

logger = logging.getLogger(__name__)

class ConnectionManager:
    """Production-grade WebSocket connection manager."""

    def __init__(
        self,
        max_connections: int = 500,
        max_per_lobby: int = 10,
    ):
        self.max_connections = max_connections
        self.max_per_lobby = max_per_lobby

        # lobby_code -> set of websockets
        self.active_connections: Dict[str, Set[WebSocket]] = {}

        # websocket -> (lobby_code, user_id)
        self.connection_info: Dict[WebSocket, Tuple[str, str]] = {}

        # user_id -> websocket (for direct messaging)
        self.user_connections: Dict[str, WebSocket] = {}

        # Health monitoring
        self._pending_pings: Dict[str, asyncio.Event] = {}
        self._last_message_times: Dict[str, float] = {}

    def can_accept_connection(self, lobby_code: str) -> Tuple[bool, str]:
        """Check if we can accept a new connection."""
        total = sum(len(conns) for conns in self.active_connections.values())
        if total >= self.max_connections:
            return False, "server_full"

        lobby_count = len(self.active_connections.get(lobby_code, set()))
        if lobby_count >= self.max_per_lobby:
            return False, "lobby_full"

        return True, ""

    async def connect(
        self,
        websocket: WebSocket,
        lobby_code: str,
        user_id: str,
    ) -> None:
        """Accept and register a WebSocket connection."""
        await websocket.accept()

        if lobby_code not in self.active_connections:
            self.active_connections[lobby_code] = set()
        self.active_connections[lobby_code].add(websocket)

        self.connection_info[websocket] = (lobby_code, user_id)
        self.user_connections[user_id] = websocket
        self._last_message_times[user_id] = time.time()

    def disconnect(self, websocket: WebSocket) -> Optional[Tuple[str, str]]:
        """Remove a WebSocket connection."""
        info = self.connection_info.get(websocket)
        if not info:
            return None

        lobby_code, user_id = info

        if lobby_code in self.active_connections:
            self.active_connections[lobby_code].discard(websocket)
            if not self.active_connections[lobby_code]:
                del self.active_connections[lobby_code]

        del self.connection_info[websocket]
        self.user_connections.pop(user_id, None)
        self._last_message_times.pop(user_id, None)
        self._pending_pings.pop(user_id, None)

        return info

    async def broadcast_to_lobby(
        self,
        lobby_code: str,
        message: dict,
        exclude_user_id: Optional[str] = None,
    ) -> int:
        """Broadcast message to all connections in a lobby."""
        if lobby_code not in self.active_connections:
            return 0

        data = json.dumps(message)
        disconnected = []
        sent_count = 0

        for websocket in self.active_connections[lobby_code]:
            if exclude_user_id:
                info = self.connection_info.get(websocket)
                if info and info[1] == exclude_user_id:
                    continue

            try:
                await websocket.send_text(data)
                sent_count += 1
            except Exception:
                disconnected.append(websocket)

        for ws in disconnected:
            self.disconnect(ws)

        return sent_count

    async def send_to_user(self, user_id: str, message: dict) -> bool:
        """Send message to a specific user."""
        websocket = self.user_connections.get(user_id)
        if not websocket:
            return False

        try:
            await websocket.send_text(json.dumps(message))
            return True
        except Exception:
            self.disconnect(websocket)
            return False

    async def ping_user(self, user_id: str, timeout: float = 2.0) -> Tuple[bool, Optional[float]]:
        """Send health check ping and wait for pong."""
        websocket = self.user_connections.get(user_id)
        if not websocket:
            return False, None

        ping_event = asyncio.Event()
        self._pending_pings[user_id] = ping_event

        start_time = time.time()

        try:
            await websocket.send_text(json.dumps({
                "type": "health_ping",
                "timestamp": start_time
            }))

            try:
                await asyncio.wait_for(ping_event.wait(), timeout=timeout)
                latency_ms = (time.time() - start_time) * 1000
                return True, latency_ms
            except asyncio.TimeoutError:
                return False, None
        finally:
            self._pending_pings.pop(user_id, None)

    def record_pong(self, user_id: str) -> None:
        """Record pong response from user."""
        self._last_message_times[user_id] = time.time()
        ping_event = self._pending_pings.get(user_id)
        if ping_event:
            ping_event.set()

    def update_last_message(self, user_id: str) -> None:
        """Update last message timestamp."""
        self._last_message_times[user_id] = time.time()

    def is_user_connected(self, user_id: str) -> bool:
        return user_id in self.user_connections

    def get_lobby_users(self, lobby_code: str) -> Set[str]:
        users = set()
        for ws in self.active_connections.get(lobby_code, set()):
            info = self.connection_info.get(ws)
            if info:
                users.add(info[1])
        return users

    def get_stats(self) -> dict:
        total = sum(len(conns) for conns in self.active_connections.values())
        return {
            "total_connections": total,
            "max_connections": self.max_connections,
            "capacity_percent": round(total / self.max_connections * 100, 1),
            "active_lobbies": len(self.active_connections),
        }

manager = ConnectionManager()

TypeScript (Client)

class WebSocketClient {
  private ws: WebSocket | null = null;

  connect(url: string) {
    this.ws = new WebSocket(url);

    this.ws.onmessage = (event) => {
      const message = JSON.parse(event.data);

      // Respond to health pings immediately
      if (message.type === 'health_ping') {
        this.ws?.send(JSON.stringify({
          type: 'health_pong',
          timestamp: message.timestamp
        }));
        return;
      }

      this.handleMessage(message);
    };
  }

  private handleMessage(message: any) {
    // Your message handling logic
  }
}

Usage Examples

FastAPI Endpoint

@app.websocket("/ws/{lobby_code}")
async def websocket_endpoint(
    websocket: WebSocket,
    lobby_code: str,
    token: str = Query(...),
):
    user_id = await authenticate_token(token)
    if not user_id:
        await websocket.close(code=4001, reason="unauthorized")
        return

    can_accept, reason = manager.can_accept_connection(lobby_code)
    if not can_accept:
        await websocket.close(code=4002, reason=reason)
        return

    await manager.connect(websocket, lobby_code, user_id)

    try:
        while True:
            data = await websocket.receive_json()
            manager.update_last_message(user_id)

            if data.get("type") == "health_pong":
                manager.record_pong(user_id)
                continue

            await handle_message(lobby_code, user_id, data)
    except WebSocketDisconnect:
        manager.disconnect(websocket)

Best Practices

  1. Check capacity before accepting - Reject early with clear reason
  2. Track by user ID - Enable direct messaging and presence queries
  3. Ping/pong health checks - Detect stale connections (every 15-30s)
  4. Clean up on send failure - Remove connections that fail to receive
  5. Log connection events - Track connects, disconnects, and capacity

Common Mistakes

  • Not checking capacity before accepting connections
  • Missing user-to-connection mapping (can't send direct messages)
  • No health verification (stale connections accumulate)
  • Not cleaning up failed sends (resource leaks)
  • Forgetting to handle WebSocketDisconnect exception

Related Patterns

  • sse-streaming - Server-Sent Events alternative
  • graceful-shutdown - Drain connections on shutdown
  • rate-limiting - Rate limit WebSocket messages

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

38.51%
按下载量换算72

Claude

29.57%
按下载量换算55

Cursor

19.23%
按下载量换算36

Gemini CLI

8.41%
按下载量换算16

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills