由 micah 出售

Socket.IO enables real-time, bidirectional, event-based communication between Node.js servers and clients. It supports WebSocket, long-polling fallback, namespaces, rooms, binary data, and horizontal scaling.
This block provides the Socket.IO server library (socket.io), enabling real-time bidirectional event-based communication between Node.js servers and clients over WebSocket (with HTTP long-polling fallback). It is aimed at backend engineers building chat systems, collaborative tools, live dashboards, or any application requiring persistent, low-latency connections.
client-dist/ - Pre-built Socket.IO client bundles (plain, minified, ESM, msgpack variants) served automatically to browserslib/ - TypeScript source for the entire server: Server class, Namespace, Socket, adapters, typed event emitter, broadcast operator, uWebSockets.js supportwrapper.mjs - ESM re-export shim exposing Server, Namespace, and Socket as named exportsCHANGELOG.md - Version history and migration notesLICENSE - MIT license textRELEASING.md - Internal release process documentationReadme.md - Project overview and links to official documentationpackage.json - Package manifest with scripts, exports map, and metadatatsconfig.json - TypeScript compiler configuration for building the librarylib/broadcast-operator.ts - BroadcastOperator and RemoteSocket types for targeting rooms/namespaceslib/client.ts - Internal Client class representing a raw engine.io connectionlib/index.ts - Main entry point; exports Server class and all public typeslib/namespace.ts - Namespace class and ExtendedError typelib/parent-namespace.ts - ParentNamespace for dynamic namespace matchinglib/socket-types.ts - DisconnectReason and shared socket type definitionslib/socket.ts - Socket class representing a single connected client socketlib/typed-events.ts - Generic strongly-typed event emitter infrastructurelib/uws.ts - uWebSockets.js (uServer) adapter helpersnpm install engine.io socket.io-adapter socket.io-parser accepts cors debug
npm install --save-dev @types/node @types/cors typescript
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 c523a7b72e6b0f7b…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
No native build steps, pod installs, or Android linking are required. This is a pure Node.js library.
Copy the source/ directory into your project, e.g. src/vendor/socket.io/.
In tsconfig.json, ensure "moduleResolution" is "node" or "bundler" and that "esModuleInterop": true is set:
{
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"outDir": "dist",
"strict": true
}
}
Add a path alias so your app imports resolve to the local source:
{
"compilerOptions": {
"paths": {
"socket.io": ["src/vendor/socket.io/lib/index.ts"]
}
}
}
No environment variables are required. Optional debug output is controlled via:
DEBUG=socket.io:* node dist/server.js
If using ESM ("type": "module" in package.json), import via the wrapper shim:
import { Server, Namespace, Socket } from './vendor/socket.io/wrapper.mjs';
import { Server } from './vendor/socket.io/lib/index';
new Server(httpServer?: HTTPServer | HTTPSServer | Http2Server | number, opts?: Partial<ServerOptions>): Server
The central class. Attach it to an existing HTTP server or pass a port number and it creates one internally. Use server.on('connection', ...) or server.on('connect', ...) to handle incoming sockets. Supports namespacing via server.of('/path').
import { Namespace, ExtendedError } from './vendor/socket.io/lib/namespace';
// Accessed via server.of(name)
namespace.use((socket, next: (err?: ExtendedError) => void) => void): Namespace
namespace.on('connection', (socket: Socket) => void): Namespace
Represents a communication channel identified by a path (default '/'). Use namespace.use() for middleware (authentication, logging) and .on('connection') to handle sockets joining that namespace. Multiple namespaces share a single underlying TCP connection per client.
import { Socket } from './vendor/socket.io/lib/socket';
import { DisconnectReason } from './vendor/socket.io/lib/socket-types';
socket.emit(event: string, ...args: any[]): boolean
socket.on(event: string, listener: (...args: any[]) => void): Socket
socket.join(room: string | string[]): Promise<void>
socket.to(room: string): BroadcastOperator
socket.disconnect(close?: boolean): Socket
Represents a single connected client within a namespace. Use socket.join() to assign the client to rooms, socket.to(room).emit() to broadcast to a subset of clients, and socket.disconnect() to forcibly close the connection.
Attach Socket.IO to a Node.js HTTP server, handle connections, and emit a welcome event.
import { createServer } from 'http';
import { Server } from './vendor/socket.io/lib/index';
const httpServer = createServer();
const io = new Server(httpServer, {
cors: { origin: '*' }
});
io.on('connection', (socket) => {
console.log('client connected:', socket.id);
socket.emit('welcome', { message: 'Hello from server' });
socket.on('ping', (cb) => {
cb('pong');
});
socket.on('disconnect', (reason) => {
console.log('client disconnected:', reason);
});
});
httpServer.listen(3000, () => {
console.log('listening on port 3000');
});
Use a custom namespace with authentication middleware to reject unauthorized connections.
import { createServer } from 'http';
import { Server, ExtendedError } from './vendor/socket.io/lib/index';
const httpServer = createServer();
const io = new Server(httpServer);
const adminNsp = io.of('/admin');
adminNsp.use((socket, next) => {
const token = socket.handshake.auth?.token as string | undefined;
if (token === 'secret-admin-token') {
return next();
}
const err = new Error('unauthorized') as ExtendedError;
err.data = { code: 401 };
next(err);
});
adminNsp.on('connection', (socket) => {
console.log('admin connected:', socket.id);
socket.emit('admin:ready');
socket.on('admin:broadcast', (payload: unknown) => {
adminNsp.emit('admin:message', payload);
});
});
httpServer.listen(3001);
Join clients to rooms and broadcast targeted messages.
import { createServer } from 'http';
import { Server } from './vendor/socket.io/lib/index';
const httpServer = createServer();
const io = new Server(httpServer);
io.on('connection', (socket) => {
socket.on('join-room', async (roomId: string) => {
await socket.join(roomId);
// Notify everyone else in the room
socket.to(roomId).emit('user-joined', { id: socket.id });
socket.emit('joined', { room: roomId });
});
socket.on('room-message', (roomId: string, text: string) => {
// Broadcast to everyone in the room including sender
io.to(roomId).emit('room-message', { from: socket.id, text });
});
socket.on('leave-room', async (roomId: string) => {
await socket.leave(roomId);
socket.to(roomId).emit('user-left', { id: socket.id });
});
});
httpServer.listen(3002);
client-dist/ - Static browser client bundles; the server automatically serves these at /socket.io/socket.io.js during handshake.wrapper.mjs - Thin ESM shim re-exporting Server, Namespace, and Socket for projects using "type": "module".lib/index.ts - Main entry: defines and exports the Server class, all option types, and re-exports symbols from sub-modules.lib/namespace.ts - Namespace class managing per-path socket collections, middleware stacks, and room broadcasts; also exports ExtendedError.lib/socket.ts - Socket class with per-connection event handling, room management, acknowledgements, and timeout utilities.lib/socket-types.ts - Shared type definitions including DisconnectReason string union.lib/broadcast-operator.ts - Fluent BroadcastOperator for chaining .to(), .except(), .timeout() before .emit().lib/parent-namespace.ts - ParentNamespace supporting regex/function-based dynamic namespace creation.lib/client.ts - Internal Client bridges a raw engine.io socket to one or more namespace Socket instances.lib/typed-events.ts - Generic StrictEventEmitter and helper types (EventsMap, EventNames, AllButLast, etc.) for typed event APIs.lib/uws.ts - Helpers (patchAdapter, restoreAdapter, serveFile) for running Socket.IO on uWebSockets.js instead of the built-in HTTP server.package.json - Defines exports map, engine.io peer range, build scripts, and package metadata.tsconfig.json - Compiler options used when building the library from TypeScript source.lib/index.ts uses import X = require(...) (CJS-style). Set "esModuleInterop": true and "module": "CommonJS" in tsconfig.json or imports will fail at compile time.engine.io peer: The Server constructor calls attach() from engine.io directly; pin engine.io to the same major version referenced in the original package.json to avoid API mismatches.cors options are not passed to new Server(...). Always supply { cors: { origin: '<your-origin>' } } in production.socket.io-adapter version mismatch: SessionAwareAdapter and Room/SocketId types are imported from socket.io-adapter; mismatched versions produce TypeScript errors on those types. Pin to the version in the original package.json.lib/uws.ts patches the adapter only when uServer from engine.io is used. Do not call patchAdapter/restoreAdapter unless you have explicitly configured the uWS transport./socket.io, it will shadow the auto-served client bundle. Rename your static route or disable client serving via { serveClient: false }.I have a copy of the socket.io server library (upstream package: socket.io)
located at `source/` in my project, with a USAGE.md integration guide at
`source/USAGE.md`.
Please help me integrate this library into my existing Node.js/TypeScript project
step by step:
1. Read `source/USAGE.md` and `source/lib/index.ts` to understand the public API.
2. Install all required dependencies listed in USAGE.md.
3. Update my tsconfig.json to resolve `socket.io` imports to `source/lib/index.ts`.
4. Create a `src/socket-server.ts` file that:
- Attaches a Socket.IO Server to my existing Express HTTP server.
- Adds authentication middleware on the default namespace using socket.handshake.auth.
- Handles 'connection', 'disconnect', and at least one custom event with room broadcasting.
5. Export the `io` instance so other modules can emit server-side events.
6. Show me how to import and use `Socket`, `Namespace`, and `DisconnectReason`
from `source/lib/index.ts` with correct TypeScript types.
7. Warn me about any pitfalls described in USAGE.md that apply to my setup.
Use only the exports visible in `source/lib/index.ts` and `source/wrapper.mjs`.
Do not invent any APIs not present in those files.
This library is released under the MIT License (see source/LICENSE). It is developed and maintained by the Socket.IO team. Upstream repository and documentation: https://github.com/socketio/socket.io. Full API reference: https://socket.io/docs/v4/.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费