socketio

添加基于 Socket.IO 的实时通信功能。适用于需要构建实时功能、添加 WebSocket 通信、开发聊天应用、实现实时通知、创建协同编辑、流式传输实时数据、构建实时仪表盘、添加在线状态指示器或在 Web 应用中实现发布/订阅消息传递的场景。涵盖服务端设置、客户端连接、rooms 与 namespaces、身份验证、使用 Redis 适配器进行扩展以及与 Next.js 的集成。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "socketio":https://skillpi.com/zh/skills/deepskill-cf51829ae652ecfca12f6eb4612589337c8477c5917d56e31b31a90312639f54。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

添加基于 Socket.IO 的实时通信功能。适用于需要构建实时功能、添加 WebSocket 通信、开发聊天应用、实现实时通知、创建协同编辑、流式传输实时数据、构建实时仪表盘、添加在线状态指示器或在 Web 应用中实现发布/订阅消息传递的场景。涵盖服务端设置、客户端连接、rooms 与 namespaces、身份验证、使用 Redis 适配器进行扩展以及与 Next.js 的集成。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: socketio
description: >-
  Add real-time communication with Socket.IO. Use when a user asks to build
  real-time features, add WebSocket communication, build a chat application,
  implement live notifications, create collaborative editing, stream live data,
  build real-time dashboards, add presence indicators, or implement pub/sub
  messaging in a web app. Covers server setup, client connection, rooms,
  namespaces, authentication, scaling with Redis adapter, and Next.js integration.
license: Apache-2.0
compatibility: 'Node.js 16+ (server), any browser (client)'
metadata:
  author: terminal-skills
  version: 1.0.0
  category: development
  tags:
    - socketio
    - websocket
    - realtime
    - chat
    - live
    - events

Socket.IO

Overview

Socket.IO is the most popular real-time communication library for Node.js. It provides bidirectional event-based communication between client and server, with automatic fallback from WebSocket to HTTP long-polling, reconnection handling, room-based broadcasting, and namespace isolation. This skill covers server setup, client integration, rooms, authentication middleware, scaling with Redis, and common patterns like chat, notifications, and presence.

Instructions

Step 1: Installation

# Server
npm install socket.io

# Client
npm install socket.io-client

# Redis adapter (for scaling across multiple servers)
npm install @socket.io/redis-adapter redis

Step 2: Server Setup

// server.ts — Socket.IO server with Express
import { createServer } from 'http'
import { Server } from 'socket.io'
import express from 'express'

const app = express()
const httpServer = createServer(app)

const io = new Server(httpServer, {
  cors: {
    origin: 'http://localhost:3000',    // frontend URL
    methods: ['GET', 'POST'],
  },
  pingTimeout: 60000,
  pingInterval: 25000,
})

io.on('connection', (socket) => {
  console.log(`Connected: ${socket.id}`)

  // Listen for events from this client
  socket.on('message', (data) => {
    console.log(`Message from ${socket.id}:`, data)

    // Broadcast to all other clients
    socket.broadcast.emit('message', {
      ...data,
      senderId: socket.id,
      timestamp: Date.now(),
    })
  })

  // Rooms — group clients together
  socket.on('join-room', (roomId) => {
    socket.join(roomId)
    io.to(roomId).emit('user-joined', { userId: socket.id, roomId })
  })

  socket.on('leave-room', (roomId) => {
    socket.leave(roomId)
    io.to(roomId).emit('user-left', { userId: socket.id })
  })

  // Send to specific room
  socket.on('room-message', ({ roomId, message }) => {
    io.to(roomId).emit('message', { message, senderId: socket.id })
  })

  socket.on('disconnect', (reason) => {
    console.log(`Disconnected: ${socket.id}, reason: ${reason}`)
  })
})

httpServer.listen(3001, () => console.log('Socket.IO server on :3001'))

Step 3: Client Connection

// hooks/useSocket.ts — React hook for Socket.IO client
import { useEffect, useRef, useState, useCallback } from 'react'
import { io, Socket } from 'socket.io-client'

export function useSocket(url: string = 'http://localhost:3001') {
  const socketRef = useRef<Socket | null>(null)
  const [isConnected, setIsConnected] = useState(false)

  useEffect(() => {
    const socket = io(url, {
      autoConnect: true,
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
    })

    socket.on('connect', () => setIsConnected(true))
    socket.on('disconnect', () => setIsConnected(false))

    socketRef.current = socket

    return () => {
      socket.disconnect()
    }
  }, [url])

  const emit = useCallback((event: string, data: any) => {
    socketRef.current?.emit(event, data)
  }, [])

  const on = useCallback((event: string, handler: (...args: any[]) => void) => {
    socketRef.current?.on(event, handler)
    return () => { socketRef.current?.off(event, handler) }
  }, [])

  return { socket: socketRef.current, isConnected, emit, on }
}

Step 4: Authentication Middleware

// middleware/socket-auth.ts — Authenticate WebSocket connections
import { Server } from 'socket.io'
import jwt from 'jsonwebtoken'

export function setupAuth(io: Server) {
  io.use((socket, next) => {
    /**
     * Verify JWT token from handshake auth.
     * Rejects connections without valid authentication.
     */
    const token = socket.handshake.auth.token

    if (!token) {
      return next(new Error('Authentication required'))
    }

    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET!)
      socket.data.userId = (decoded as any).userId
      socket.data.userName = (decoded as any).userName
      next()
    } catch {
      next(new Error('Invalid token'))
    }
  })
}

// Client-side: pass token on connection
// const socket = io('http://localhost:3001', { auth: { token: 'user-jwt-token' } })

Step 5: Scaling with Redis Adapter

// server-scaled.ts — Scale Socket.IO across multiple server instances
import { Server } from 'socket.io'
import { createAdapter } from '@socket.io/redis-adapter'
import { createClient } from 'redis'

const pubClient = createClient({ url: 'redis://localhost:6379' })
const subClient = pubClient.duplicate()

await pubClient.connect()
await subClient.connect()

const io = new Server(httpServer)
io.adapter(createAdapter(pubClient, subClient))
// Now events are broadcast across all server instances via Redis pub/sub

Step 6: Presence (Online Status)

// presence.ts — Track who's online in real-time
const onlineUsers = new Map<string, { socketId: string; userName: string }>()

io.on('connection', (socket) => {
  const userId = socket.data.userId
  const userName = socket.data.userName

  // Mark online
  onlineUsers.set(userId, { socketId: socket.id, userName })
  io.emit('presence-update', { userId, userName, status: 'online' })

  // Send current online list to newly connected user
  socket.emit('online-users', Array.from(onlineUsers.entries()).map(([id, data]) => ({
    userId: id,
    userName: data.userName,
    status: 'online',
  })))

  socket.on('disconnect', () => {
    onlineUsers.delete(userId)
    io.emit('presence-update', { userId, userName, status: 'offline' })
  })
})

Examples

Example 1: Build a real-time chat application

User prompt: "Build a group chat where users join rooms, see who's online, and messages appear instantly."

The agent will:

  1. Set up Socket.IO server with room support and authentication.
  2. Build React components: ChatRoom, MessageList, UserList, MessageInput.
  3. Implement join/leave room events with member lists.
  4. Add typing indicators and read receipts.
  5. Scale with Redis adapter for multi-server deployment.

Example 2: Add live notifications to a SaaS app

User prompt: "When a user is mentioned in a comment, show a real-time notification bell update without page refresh."

The agent will:

  1. Connect Socket.IO on app load with user authentication.
  2. Server sends notification events when comments mention a user.
  3. Client updates the notification count badge in real-time.
  4. Clicking the bell shows the notification panel with mark-as-read.

Guidelines

  • Socket.IO is not raw WebSocket — it's a higher-level protocol with its own framing. Socket.IO clients can only connect to Socket.IO servers, and vice versa. For raw WebSocket, use the ws package.
  • Always add authentication middleware — without it, anyone can connect and listen to events.
  • Use rooms for grouping (chat rooms, document collaboration sessions, team channels). They're more efficient than manually managing arrays of socket IDs.
  • For production with multiple server instances, the Redis adapter is mandatory — without it, events only reach clients connected to the same server.
  • Emit minimal data — Socket.IO messages are not compressed by default. Send IDs and let the client fetch details, rather than sending large objects over WebSocket.
  • Handle reconnection gracefully — Socket.IO auto-reconnects, but the client should re-join rooms and re-sync state after reconnection.

当前收录版本

1.0.0

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 提供 Socket.IO 实时通信的完整端到端解决方案,覆盖服务端、客户端、认证、扩展等关键环节
  • 适用于聊天应用、实时通知、协同编辑、仪表盘等多个高价值场景,实用性强
触发精准95/100

亮点

  • 触发词精准覆盖多种实时功能需求,边界清晰,用户易匹配
结构规范90/100

待提升项

  • 缺少 When to Use 显式章节 原报告严重程度:轻微

    虽然在 frontmatter 和 overview 中描述了使用场景,但未在正文设置独立的 'When to Use' 章节

    改进建议:建议在 Overview 后添加独立的 'When to Use' 章节,更清晰地引导用户

亮点

  • 步骤划分清晰,每步含完整代码示例,结构良好
  • 提供两个端到端示例,帮助用户理解实际应用场景
执行可靠90/100

亮点

  • 工具来源明确,参数配置合理,覆盖认证、重连、扩展等关键可靠性问题
  • Redis 适配器说明到位,确保多服务器部署下的消息一致性
证据可验 (前四项均值)90/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 安装或获取外部依赖

    使用官方来源并锁定版本,在隔离环境检查安装脚本。当前文档检查不覆盖后续下载的代码。

    主文档提及 · 第 37, 40, 43 行
文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • localhost

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。