Community程式設計與開發github.com

socketio-docs

根據官方 Socket.IO v4 文件建置、設定與除錯 Socket.IO 4.8 伺服器與客戶端。在撰寫 Node.js Socket.IO 伺服器(Express、Fastify、Koa、Bun、uWebSockets.js)或 socket.io-client 應用程式時使用。

socketio-docs 是什麼?

此技能封裝了 Socket.IO 4.8 的官方文件,特別聚焦於那些易於出錯的規則與陷阱。它涵蓋了連線與身份識別、事件與確認、廣播與房間、傳遞保證、CORS 與部署設定等面向。技能中包含多個程式碼範例,示範正確的實作方式,例如使用 `emitWithAck`、`timeout()`、連線狀態恢復等進階功能。此技能支援所有主流 Node.js 框架(Express、Fastify、Koa、Bun、uWebSockets.js)以及客戶端應用程式,並提供遷移指南(v2/v3→v4)。無論你是 Socket.IO 新手還是有經驗的開發者,此技能都能幫助你避免常見錯誤,並確保即時通訊應用的穩定性與可擴展性。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/quentin-autret/claude-skills/tree/main/skills/socketio-docs

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Socket.IO 4.8

概觀

此技能包含了 Socket.IO 4.8 中容易出錯的規則:使用短暫的 socket.id 作為使用者鍵值、監聽器重複註冊、確認回呼因 timeout() 而改變形狀、無法保護 WebSocket 的 CORS、負載平衡器後遺忘的黏性連線,以及 v2 或 v3 中不再運作的 API。每項說明都附有頁面 URL。參考檔案按領域儲存了詳細資訊。

涵蓋的版本

Socket.IO 4.8(伺服端 socket.io,客戶端 socket.io-client),文件 v4。JS 客戶端 3.x 與 4.x 可與伺服端 3.x 與 4.x 通訊。https://socket.io/docs/v4/client-installation/#version-compatibility

快速開始

import express from "express";
import { createServer } from "node:http";
import { Server } from "socket.io";

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, { cors: { origin: ["https://example.com"] } });

io.on("connection", (socket) => {
  socket.on("hello", (arg, callback) => callback("got it"));
});

httpServer.listen(3000);

https://socket.io/docs/v4/server-initialization/#with-express

import { io } from "socket.io-client";
const socket = io("https://server-domain.com", { auth: { token: "abc" } });
const answer = await socket.timeout(5000).emitWithAck("hello", "world");

https://socket.io/docs/v4/client-api/#socketemitwithackeventname-args

規則與陷阱

連線與身份

  • Socket.IO 並非 WebSocket 實作:純 WebSocket 客戶端無法連接 Socket.IO 伺服器,且 Socket.IO 客戶端也無法連接純 WebSocket 伺服器。https://socket.io/docs/v4/#what-socketio-is-not
  • 除非啟用連線狀態恢復,否則 socket.id 會在每次重新連線與頁面重新整理時改變,每個分頁的值都不同,且沒有訊息佇列。請使用您自己的 session ID(透過 cookie 或 auth 傳送)來識別使用者,並透過以使用者 ID 命名的房間來觸及使用者的每個分頁。https://socket.io/docs/v4/server-socket-instance/#socketid
io.on("connection", async (socket) => {
  const userId = await computeUserIdFromHeaders(socket.handshake.headers);
  socket.join(userId);
  io.to(userId).emit("hi");
});

https://socket.io/docs/v4/rooms/#sample-use-cases

  • 在連線中介軟體中使用 socket.handshake.auth 進行驗證。請在每個程式碼路徑中都呼叫 next(),否則連線將一直懸掛,直到逾時後被關閉。next(err) 會以 connect_error 的形式到達客戶端,err.data 則提供詳細資訊。https://socket.io/docs/v4/middlewares/
io.use((socket, next) => {
  if (isValid(socket.handshake.auth.token)) return next();
  const err = new Error("not authorized");
  err.data = { content: "Please retry later" };
  next(err);
});

https://socket.io/docs/v4/middlewares/#handling-middleware-error

事件與確認

const responses = await io.timeout(10000).emitWithAck("some-event");

https://socket.io/docs/v4/server-api/#serveremitwithackeventname-args

廣播與房間

傳遞

  • 預設保證是「至多一次」,伺服器不儲存任何訊息:斷線的客戶端將永遠錯過廣播。請使用資料庫根據 auth 中傳送的偏移量進行重播,或啟用連線狀態恢復。https://socket.io/docs/v4/delivery-guarantees#at-most-once
  • 客戶端在離線時會緩衝發送的事件,並在重新連線時刷新。請檢查 socket.connected 或對於可丟棄的資料使用 socket.volatile.emit(...)。https://socket.io/docs/v4/client-offline-behavior/#buffered-events
  • 客戶端到伺服器的「至少一次」:io({ retries: 3, ackTimeout: 10000 })。要實現「恰好一次」,請在唯一約束下儲存客戶端產生的 ID。在成功時確認,並在遇到重複時也確認,但不要在遇到任何其他錯誤時確認,這樣客戶端會因為逾時而重試。https://socket.io/docs/v4/tutorial/step-8
  • 連線狀態恢復是選擇加入的,需要一個有界線的 maxDisconnectionDuration,並且可能失敗:請根據 socket.recovered 進行分支處理。Redis(Pub/Sub)適配器不支援此功能,但 Redis Streams 適配器支援。https://socket.io/docs/v4/connection-state-recovery
const io = new Server(httpServer, {
  connectionStateRecovery: { maxDisconnectionDuration: 2 * 60 * 1000, skipMiddlewares: false },
});

https://socket.io/docs/v4/connection-state-recovery#usage

CORS 與部署

參考檔案

檔案閱讀目的
references/server-setup.md安裝、與 Express、Koa、Fastify、Hono、HTTPS、HTTP/2、Bun、uWebSockets.js 的初始設定、伺服器選項與預設值、打包、處理函式佈局
references/middleware-and-auth.md連線、socket 與引擎中介軟體、憑證、使用者身份、標頭鉤子、allowRequest、客戶端憑證
references/cors-and-proxies.mdCORS 選項與錯誤、cookies、nginx、Apache、Caddy、http-proxy、雲端負載平衡器、與 ws 共用連接埠
references/server-api.mdServer 與 Socket 實例、io 上的命名空間、工具方法、serverSideEmit、斷線原因、引擎事件與錯誤碼、關閉
references/client.md套件、初始化、Socket 事件、connect_error 與 disconnect、Manager 與多路複用、所有客戶端選項、打包工具
references/events-rooms-namespaces.md序列化、確認、捕獲所有事件的監聽器、驗證、錯誤處理、廣播、房間、動態命名空間
references/delivery-and-recovery.md傳遞保證、重試、恰好一次、偏移量重播、連線狀態恢復
references/multiple-nodes.md黏性連線、多節點的代理伺服器設定、替代方案、Node.js 叢集、PM2
references/adapters.mdRedis、分片 Redis、Redis Streams、Postgres、MongoDB、叢集、AWS SQS、Azure、GCP 適配器、功能矩陣、發射器
references/performance-and-operations.md原生附加元件、wsEngine、記憶體、自訂解析器、作業系統限制、負載測試、Admin UI、除錯日誌
references/typescript.md伺服端、客戶端與命名空間上的事件介面、SocketData、型別化測試
references/testing-and-troubleshooting.md伺服器整合測試、使用虛擬 socket 的客戶端測試、連線失敗、斷線、卡住的 long-polling
references/migrations-and-protocol.mdv2 到 v3 與 v3 到 v4 的變更、使用 allowEIO3 的滾動升級、Engine.IO 與 Socket.IO 有線協定

舊有模式

舊用法替代方案來源
origins 或 handlePreflightRequest 選項cors: { origin: [...] }https://socket.io/docs/v4/migrating-from-2-x-to-3-0/#cors-handling
io.set("authorization", fn)io.use((socket, next) => ...)https://socket.io/docs/v4/migrating-from-2-x-to-3-0/#ioset-is-removed
Socket query 選項中的 Tokenauth 選項,讀取為 socket.handshake.authhttps://socket.io/docs/v4/migrating-from-2-x-to-3-0/
客戶端拒絕連線時的 error 事件connect_error,包含 err.message 與 err.datahttps://socket.io/docs/v4/migrating-from-2-x-to-3-0/
Socket 上的 socket.on("reconnect_attempt")Manager 上的 socket.io.on("reconnect_attempt")https://socket.io/docs/v4/client-socket-instance/#events
客戶端用於延遲的 pong 事件在間隔中使用 socket.volatile.emit("ping", cb)https://socket.io/docs/v4/migrating-from-2-x-to-3-0/#no-more-pong-event-for-retrieving-latency
Namespace.connected 物件Namespace.sockets,一個 Maphttps://socket.io/docs/v4/migrating-from-2-x-to-3-0/
Object.keys(socket.rooms)socket.rooms 是一個 Sethttps://socket.io/docs/v4/migrating-from-2-x-to-3-0/
socket.join(room, cb)socket.join(room),使用非同步適配器搭配 awaithttps://socket.io/docs/v4/migrating-from-2-x-to-3-0/
Namespace.clients(cb)(v2),然後 allSockets()(v3,將在下一個主要版本中移除)fetchSockets()https://socket.io/docs/v4/server-api/#namespaceallsockets
socket.binary(false)自訂 parserhttps://socket.io/docs/v4/migrating-from-2-x-to-3-0/
socket.emit("a").emit("b")分開呼叫,emit() 返回 truehttps://socket.io/docs/v4/migrating-from-2-x-to-3-0/
socket.io 或 socket.io-client 的預設匯入命名匯入 import { Server } from "socket.io" 或 import { io } from "socket.io-client"https://socket.io/docs/v4/migrating-from-3-x-to-4-0/#syntax-changes

Individual skills in this repo

This repo contains 16 individual skills — each has its own dedicated page.

eslint-docs

Teaches current ESLint 10 practices drawn from the official documentation. Use when writing, reviewing or fixing an eslint.config.js (flat config, defineConfig, files, ignores, globalIgnores, extends, languageOptions, globals, parsers, processors), configuring ESLint rules and severities, disable comments and inline config, running the CLI in CI (--fix, --cache, --quiet, --max-warnings, bulk suppressions, formatters, feature flags, MCP server), writing custom rules (meta, schema, fixes, suggestions, selectors, scope, code paths) and testing them with RuleTester, building plugins, shareable configs, custom parsers, processors or formatters, using the Node.js API (ESLint, Linter), or migrating to ESLint 9 or 10 from eslintrc. Triggers on eslint, eslint.config.js, flat config, .eslintrc, .eslintignore, @eslint/js, js/recommended, eslint-disable, no-unused-vars, no-restricted-imports, no-restricted-syntax, RuleTester, eslint-plugin, eslint-config, FlatCompat, context.getScope is not a function, ESLint 10.

grafana-cloud-docs

Grafana Cloud pitfalls, defaults, limits and current patterns from the Grafana, Mimir, Loki and Tempo docs, each tied to its docs URL. Use when sending OpenTelemetry data to Grafana Cloud, writing PromQL, LogQL or TraceQL, controlling cardinality and cost, designing alert rules, routing notifications, provisioning alerting, building Synthetic Monitoring checks, using the /apis dashboard API, choosing access policy tokens or service accounts, or migrating off API keys, the Loki Exporter and legacy /api routes.

javascript-docs

Teaches current JavaScript (ECMAScript) practice drawn from the MDN JavaScript documentation. Use when writing, reviewing or fixing modern JavaScript, choosing a built-in API, or replacing a deprecated pattern. Covers equality and coercion, let/const and the temporal dead zone, strict mode, ASI, functions, classes and private fields, objects, prototypes, Proxy, Reflect, Symbol, eval, operators (??, ?., spread, BigInt arithmetic), statements, Promise, async/await, Promise.try, iterators and iterator helpers, generators, using/await using, DisposableStack, WeakRef, Array (toSorted, at, groupBy, fromAsync), Map, Set methods, WeakMap, strings and Unicode, encodeURIComponent, RegExp (v flag, RegExp.escape, lastIndex), Number, Math, BigInt, JSON (rawJSON, revivers), typed arrays, ArrayBuffer, base64, SharedArrayBuffer, Atomics, Temporal, Date, Intl (DateTimeFormat, NumberFormat, Collator, Segmenter, PluralRules), errors (cause, Error.isError), ES modules, import attributes, import.meta, dynamic import.

next-intl-docs

Teaches current next-intl 4 practices for internationalizing Next.js apps, drawn from the official documentation. Use when setting up next-intl with the App Router, writing i18n/request.ts, adding a [locale] segment with defineRouting, createMiddleware in proxy.ts (formerly middleware.ts), building locale switchers with createNavigation, translating with useTranslations or getTranslations, passing messages to NextIntlClientProvider, writing ICU messages (plurals, select, rich text), formatting dates, numbers and lists with useFormatter, translating metadata, Server Actions, Route Handlers, localized 404 and error pages, static rendering with next/root-params, type-safe messages through AppConfig, testing with Jest, Vitest, Storybook, or extracting inline messages with useExtracted. Triggers on next-intl, useTranslations, getTranslations, NextIntlClientProvider, getRequestConfig, i18n routing, locale prefix, localePrefix, NEXT_LOCALE, hreflang, setRequestLocale, ICU messages, App Router internationalization.

nodejs-docs

Teaches Node.js practice drawn from the official Node.js API documentation, with pitfalls, surprising defaults, deprecations and replacements, each backed by its nodejs.org URL. Use when writing, reviewing, debugging or upgrading Node.js code, or choosing a built-in module (fs, crypto, streams, http, process, CLI flags, node:test, ESM/CommonJS, package.json exports, TypeScript type stripping, child_process, worker_threads, node:sqlite, deprecations).

playwright-docs

Pitfalls, surprising defaults and recommended patterns of Playwright Test for JavaScript and TypeScript, distilled from the official docs. Use when writing, reviewing, debugging or configuring Playwright tests (@playwright/test, playwright.config.ts, npx playwright test), including flaky tests, locators (getByRole, filter, strict mode), web-first assertions (expect, toHaveText, toBeVisible, expect.poll, toPass), fixtures, storageState authentication, project dependencies, timeouts, retries, network mocking (page.route, routeFromHAR, routeWebSocket), API testing, clock, aria snapshots, toHaveScreenshot, axe accessibility scans, traces, UI mode, reporters, CI, Docker, sharding, test locks, component testing with stories and mount, codegen, Playwright MCP, playwright-cli and migration from Puppeteer, Protractor, Testing Library or older Playwright versions.

postgresql-docs

Pitfalls, surprising defaults, PostgreSQL 18 changes and recommended patterns from the official PostgreSQL 18 documentation, each backed by its postgresql.org URL. Use when writing or reviewing PostgreSQL SQL, schema design, migrations and ALTER TABLE locks, indexes, transactions, isolation levels and retries, locking, upsert and MERGE, COPY, JSONB, timestamptz, generated and identity columns, partitioning, EXPLAIN, vacuum, roles, row-level security, PL/pgSQL, full-text search, connection settings, and upgrades to PostgreSQL 18.

react-docs

Writes, reviews and upgrades React 19.3 code from the official react.dev documentation. Use when writing components and Hooks, removing unnecessary useEffect calls, fixing Effect dependencies with useEffectEvent, building forms with Actions (useActionState, useOptimistic, useFormStatus, form action), using Server Components, 'use client', 'use server' and Server Functions, Suspense, use(), useTransition, useDeferredValue, ViewTransition, Activity, adopting React Compiler and eslint-plugin-react-hooks, deciding on useMemo, useCallback and memo, server rendering and hydration (createRoot, hydrateRoot, renderToPipeableStream, prerender), or migrating from React 18 (forwardRef, Context.Provider, ReactDOM.render, propTypes, defaultProps). Triggers on React, JSX, hooks, useState, useEffect, useRef, useContext, Server Components, RSC, Actions, React Compiler, Strict Mode, hydration mismatch, React 19 upgrade.

rust-std-docs

Gives current guidance from the official Rust standard library docs (std 1.99.1 stable) on pitfalls, panics, platform differences, discouraged APIs and newer stable replacements. Use when writing, reviewing or refactoring Rust code that uses std, especially collections (Vec, HashMap, BTreeMap, BinaryHeap, entry, extract_if, sort), Option/Result/error handling (expect, ?, Error, ExitCode, panic), iterators (collect, flatten, Peekable, try_fold), Box/Rc/RefCell/Cow/Pin/mem::take, Arc/Mutex/RwLock/OnceLock/LazyLock/thread::scope/mpsc/Condvar/atomics, String/str/fmt/format!/OsString/CString, io/fs/path (BufWriter, OpenOptions, PathBuf::join), process/env/net/time (Command, set_var, TcpStream, Instant, Duration), From/TryFrom/AsRef/Ord/Drop/Deref/Clone, and unsafe raw pointers, MaybeUninit, transmute, NonNull or integer overflow and float ordering.

tailwindcss-docs

Teaches current Tailwind CSS v4 practices drawn from the official documentation. Use for any task that touches Tailwind CSS v4, even a small one, because many v3 habits silently break in v4. Use when writing or reviewing Tailwind CSS v4 code (utility classes, variants, arbitrary values, theme variables in @theme, @utility, @custom-variant, @apply, @reference, @source), setting up Tailwind in a framework or build tool (Vite plugin, PostCSS plugin, CLI, Next.js, SvelteKit, Nuxt, Angular, Laravel, Rails), customizing the theme (colors, fonts, breakpoints, spacing, animations), building dark mode with a class or data attribute, or migrating a project from Tailwind v3 (tailwind.config.js, @tailwind directives, darkMode class, safelist, bg-opacity, renamed shadow and outline utilities). Triggers on tailwindcss, @import "tailwindcss", @tailwindcss/vite, @tailwindcss/postcss, @tailwindcss/cli, @theme, @custom-variant dark, npx @tailwindcss/upgrade, upgrade to Tailwind v4.

tauri-docs

Tauri 2 apps, tauri.conf.json, capabilities and permissions, commands and invoke, events and channels, plugins, bundling, signing and the updater, migration from Tauri 1. Guides Tauri 2 work from the official v2 documentation, including scopes, managed state, plugin authoring, CSP and the isolation pattern, testing and debugging, Linux, Windows and macOS packages, and mobile and store releases. Use when writing or reviewing a Tauri 2 app, adding a plugin or a capability, fixing a "not allowed" or "forbidden path" error, wiring IPC between Rust and the webview, packaging, signing or publishing a desktop or mobile build, or upgrading a Tauri 1 or 2.0 beta project.

tokio-docs

Gives current guidance from the official tokio documentation (tokio 1.54.1) on async Rust pitfalls, cancel safety, blocking code, surprising defaults and deprecated APIs. Use when writing, reviewing or debugging async Rust code that uses tokio, especially the runtime (#[tokio::main], #[tokio::test], Builder, enable_all, block_on, current_thread, LocalRuntime, shutdown, feature flags), tasks (spawn, JoinHandle, JoinSet, abort, spawn_blocking, block_in_place, LocalSet, spawn_local, task_local), select!, join!, try_join!, cancellation and graceful shutdown, sync primitives (Mutex across .await, RwLock, Semaphore, Notify, OnceCell), channels (mpsc backpressure, oneshot, broadcast lag, watch), time (sleep, interval, MissedTickBehavior, timeout, paused time, start_paused), I/O and networking (AsyncReadExt, BufWriter flush, split, io::copy, framing, TcpListener, TcpStream, UdpSocket), tokio::fs, process (Command, kill_on_drop, Child), signals (ctrl_c, Windows console events) and Windows named pipes.

typescript-docs

Configures, writes and upgrades TypeScript 6.0 code and tsconfig.json from the official TypeScript documentation. Use when upgrading from TypeScript 5.x to 6.0 (strict, types, rootDir, baseUrl, moduleResolution node, target es5, outFile, esModuleInterop), choosing module and moduleResolution, writing package.json exports and imports, fixing ESM and CommonJS interop, enabling verbatimModuleSyntax or erasableSyntaxOnly, setting up project references and tsc --build, writing .d.ts files, checking JavaScript with JSDoc, or debugging narrowing, generics, mapped types, decorators and enums. Triggers on TypeScript, tsc, tsconfig, TS5112, ignoreDeprecations, nodenext, bundler, .d.ts, @ts-check, TypeScript 6 upgrade.

typesense-docs

Pitfalls, surprising defaults and recommended patterns of the Typesense search engine, distilled from the official docs. Use when designing a Typesense collection schema, writing search parameters (q, query_by, filter_by, sort_by, facet_by, group_by), tuning typo tolerance and ranking, building vector, semantic or hybrid search, conversational RAG or natural language search, creating API keys and scoped search keys for multi-tenancy, indexing and import (JSONL, upsert, emplace, dirty_values), syncing from a primary database, reindexing through aliases, managing synonyms (synonym sets), curation sets and stopwords, joins, analytics rules and query suggestions, InstantSearch, migrating from Algolia, or running, clustering, backing up and upgrading a Typesense server.

vite-docs

Teaches current Vite 8 practices drawn from the official documentation. Use when writing or fixing a vite.config, migrating from Vite 7 (Rolldown and Oxc replacing Rollup and esbuild), configuring the dev server, proxy or HMR, handling import.meta.env and modes, tuning the production build, library mode, SSR, writing a Vite plugin, using the HMR or JavaScript API, or the Environment API. Triggers on vite.config, defineConfig, rolldownOptions, import.meta.env, loadEnv, optimizeDeps, ssrLoadModule, ModuleRunner, this.environment, upgrade to Vite 8.

vitest-docs

Teaches current Vitest 5 practices drawn from the official documentation. Use when writing, reviewing or fixing Vitest tests (test, describe, expect, test.for, fixtures with test.extend, hooks, snapshots), mocking with vi (vi.fn, vi.spyOn, vi.mock, vi.when, fake timers, stubGlobal, stubEnv), configuring vitest.config or projects, choosing an environment or pool, filtering and running tests in CI, measuring coverage with v8 or istanbul, debugging slow or flaky suites, testing components in browser mode with Playwright, or migrating from Jest, Mocha or Vitest 4. Triggers on vitest, vi.mock, vi.fn, vitest.config, toMatchSnapshot, expect.poll, coverage thresholds, browser mode, @vitest/browser-playwright, jsdom, happy-dom, migrate Jest to Vitest, upgrade Vitest 5.

相關技能