### Install Socket.IO MongoDB Adapter Source: https://socket.io/pt-br/docs/v4/mongo-adapter Command to install the necessary packages for the MongoDB adapter. ```bash npm install @socket.io/mongo-adapter mongodb ``` -------------------------------- ### MongoDB Emitter Installation Source: https://socket.io/pt-br/docs/v4/mongo-adapter Install the MongoDB emitter and the MongoDB driver for Node.js. ```APIDOC ## Emitter ### Installation ```bash npm install @socket.io/mongo-emitter mongodb ``` ``` -------------------------------- ### MongoDB Adapter Installation Source: https://socket.io/pt-br/docs/v4/mongo-adapter Install the MongoDB adapter and the MongoDB driver for Node.js. ```APIDOC ## Installation ```bash npm install @socket.io/mongo-adapter mongodb ``` For TypeScript users, you might also need `@types/mongodb`. ``` -------------------------------- ### Basic Socket.IO Server Setup (CommonJS) Source: https://socket.io/pt-br/docs/v4/tutorial/step-3 Sets up a basic Express server with Socket.IO integration. It listens for connections and serves an index.html file. Requires the 'socket.io' package. ```javascript const express = require('express'); const { createServer } = require('node:http'); const { join } = require('node:path'); const { Server } = require('socket.io'); const app = express(); const server = createServer(app); const io = new Server(server); app.get('/', (req, res) => { res.sendFile(join(__dirname, 'index.html')); }); io.on('connection', (socket) => { console.log('a user connected'); }); server.listen(3000, () => { console.log('server running at http://localhost:3000'); }); ``` -------------------------------- ### Basic Socket.IO Server Setup (ES Modules) Source: https://socket.io/pt-br/docs/v4/tutorial/step-3 Sets up a basic Express server with Socket.IO integration using ES module syntax. It listens for connections and serves an index.html file. Requires the 'socket.io' package. ```javascript import express from 'express'; import { createServer } from 'node:http'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; import { Server } from 'socket.io'; const app = express(); const server = createServer(app); const io = new Server(server); const __dirname = dirname(fileURLToPath(import.meta.url)); app.get('/', (req, res) => { res.sendFile(join(__dirname, 'index.html')); }); io.on('connection', (socket) => { console.log('a user connected'); }); server.listen(3000, () => { console.log('server running at http://localhost:3000'); }); ``` -------------------------------- ### Client Initialization for Namespaces (Same-Origin) Source: https://socket.io/pt-br/docs/v4/namespaces Provides examples of how to initialize client connections to different namespaces when the client and server are on the same origin. It shows connecting to the main namespace and specific custom namespaces like '/orders' and '/users'. ```javascript const socket = io(); // or io("/" ), the main namespace const orderSocket = io("/orders"); // the "orders" namespace const userSocket = io("/users"); // the "users" namespace ``` -------------------------------- ### Install Socket.IO Redis Adapter and Redis Source: https://socket.io/pt-br/docs/v4/redis-adapter Installs the necessary packages for using the Socket.IO Redis adapter. For TypeScript users with redis@3, @types/redis is also required. ```bash npm install @socket.io/redis-adapter redis ``` -------------------------------- ### Install Socket.IO Redis Emitter Source: https://socket.io/pt-br/docs/v4/redis-adapter Installs the package for the Socket.IO Redis emitter, which allows sending packets to connected clients from a separate Node.js process. ```bash npm install @socket.io/redis-emitter redis ``` -------------------------------- ### Creating and Emitting from Custom Namespaces (Node.js) Source: https://socket.io/pt-br/docs/v4/namespaces Demonstrates the server-side setup for a custom namespace '/my-namespace'. It shows how to listen for connections and emit messages to all clients within that specific namespace. ```javascript const nsp = io.of("/my-namespace"); sp.on("connection", socket => { console.log("someone connected"); }); sp.emit("hi", "everyone!"); ``` -------------------------------- ### Install MongoDB Emitter Source: https://socket.io/pt-br/docs/v4/mongo-adapter Command to install the MongoDB emitter package for cross-process event emission. ```bash npm install @socket.io/mongo-emitter mongodb ``` -------------------------------- ### Install Redis Streams Adapter Source: https://socket.io/pt-br/docs/v4/redis-streams-adapter Install the necessary dependencies for the Redis Streams adapter using npm. This includes the adapter package itself and the base redis client. ```bash npm install @socket.io/redis-streams-adapter redis ``` -------------------------------- ### Install Socket.IO Server Package Source: https://socket.io/pt-br/docs/v4/tutorial/step-3 Installs the socket.io package for your Node.js project and adds it as a dependency to package.json. ```bash npm install socket.io ``` -------------------------------- ### MongoDB Adapter Usage with Capped Collection Source: https://socket.io/pt-br/docs/v4/mongo-adapter Example of setting up the MongoDB adapter with a capped collection for cleaning up documents. ```APIDOC ## Usage with a capped collection ### Description This example demonstrates how to initialize the Socket.IO server with the MongoDB adapter, configuring it to use a capped collection for storing events. This method automatically handles document cleanup by enforcing a size limit on the collection. ### Method `io.adapter()` ### Endpoint N/A (Server-side configuration) ### Parameters #### Request Body N/A ### Request Example ```javascript const { Server } = require("socket.io"); const { createAdapter } = require("@socket.io/mongo-adapter"); const { MongoClient } = require("mongodb"); const DB = "mydb"; const COLLECTION = "socket.io-adapter-events"; const io = new Server(); const mongoClient = new MongoClient("mongodb://localhost:27017/?replicaSet=rs0"); const main = async () => { await mongoClient.connect(); try { await mongoClient.db(DB).createCollection(COLLECTION, { capped: true, size: 1e6 }); } catch (e) { // collection already exists } const mongoCollection = mongoClient.db(DB).collection(COLLECTION); io.adapter(createAdapter(mongoCollection)); io.listen(3000); } main(); ``` ### Response N/A (Server initialization) ``` -------------------------------- ### Room Use Cases Source: https://socket.io/pt-br/docs/v4/rooms Examples of grouping users by ID or entity association to broadcast updates to specific devices or project-related clients. ```javascript io.on("connection", async (socket) => { const userId = await computeUserIdFromHeaders(socket); socket.join(userId); io.to(userId).emit("hi"); }); io.on("connection", async (socket) => { const projects = await fetchProjects(socket); projects.forEach(project => socket.join("project:" + project.id)); io.to("project:4321").emit("project updated"); }); ``` -------------------------------- ### Import Socket.IO Client in Node.js or Build Tools Source: https://socket.io/pt-br/docs/v4/client-api Shows how to import the socket.io-client package in environments like Node.js or when using build tools. It provides examples for both ES module 'import' syntax and CommonJS 'require' syntax. ```javascript // syntaxe "import" import { io } from "socket.io-client"; ``` ```javascript // syntaxe "require" const { io } = require("socket.io-client"); ``` -------------------------------- ### Initialize Socket.IO with Redis Adapter (ioredis) Source: https://socket.io/pt-br/docs/v4/redis-adapter Integrates the Socket.IO Redis adapter using ioredis for managing Redis connections, particularly useful for Redis cluster setups. It initializes publisher and subscriber clients from an ioredis Cluster instance. ```javascript import { Server } from "socket.io"; import { createAdapter } from "@socket.io/redis-adapter"; import { Cluster } from "ioredis"; const io = new Server(); const pubClient = new Cluster([ { host: "localhost", port: 6380, }, { host: "localhost", port: 6381, }, ]); const subClient = pubClient.duplicate(); io.adapter(createAdapter(pubClient, subClient)); io.listen(3000); ``` -------------------------------- ### MongoDB Adapter Usage with TTL Index Source: https://socket.io/pt-br/docs/v4/mongo-adapter Example of setting up the MongoDB adapter with a TTL index for automatic document expiration. ```APIDOC ## Usage with a TTL index ### Description This example shows how to configure the MongoDB adapter with a Time-To-Live (TTL) index on a `createdAt` field. Documents older than the specified `expireAfterSeconds` will be automatically removed by MongoDB, providing another mechanism for cleanup. ### Method `io.adapter()` ### Endpoint N/A (Server-side configuration) ### Parameters #### Request Body N/A ### Request Example ```javascript const { Server } = require("socket.io"); const { createAdapter } = require("@socket.io/mongo-adapter"); const { MongoClient } = require("mongodb"); const DB = "mydb"; const COLLECTION = "socket.io-adapter-events"; const io = new Server(); const mongoClient = new MongoClient("mongodb://localhost:27017/?replicaSet=rs0"); const main = async () => { await mongoClient.connect(); const mongoCollection = mongoClient.db(DB).collection(COLLECTION); await mongoCollection.createIndex( { createdAt: 1 }, { expireAfterSeconds: 3600, background: true } ); io.adapter(createAdapter(mongoCollection, { addCreatedAtField: true })); io.listen(3000); } main(); ``` ### Response N/A (Server initialization) ``` -------------------------------- ### Socket.IO Acknowledgements - Receiver (JavaScript) Source: https://socket.io/pt-br/docs/v4 Example of how a Socket.IO receiver can listen for an event, process it, and send a callback response. ```javascript socket.on("hello", (arg, callback) => { console.log(arg); // "world" callback("got it"); }); ``` -------------------------------- ### Socket.IO Acknowledgements - Sender (JavaScript) Source: https://socket.io/pt-br/docs/v4 Example of how a Socket.IO sender can emit an event and wait for a response from the receiver using acknowledgements. ```javascript socket.emit("hello", "world", (response) => { console.log(response); // "conseguiu" }); ``` -------------------------------- ### Configure Manager Reconnection Settings Source: https://socket.io/pt-br/docs/v4/client-api Provides examples for configuring reconnection behavior on a Socket.IO Manager. This includes enabling/disabling reconnections, setting the maximum number of attempts, and adjusting the initial and maximum reconnection delays. ```javascript manager.reconnection(true); // Enable reconnection manager.reconnectionAttempts(5); // Set max attempts manager.reconnectionDelay(1000); // Set initial delay manager.reconnectionDelayMax(5000); // Set max delay manager.timeout(2000); // Set connection timeout ``` -------------------------------- ### Configure Cookie Options for Socket.IO Server Source: https://socket.io/pt-br/docs/v4/server-options This example shows how to set custom cookie options for the Socket.IO server, such as the cookie name, HTTP-only status, SameSite attribute, and maximum age. Note that cookies are not sent by default since Socket.IO v3. ```javascript import { Server } from "socket.io"; const io = new Server(httpServer, { cookie: { name: "my-cookie", httpOnly: true, sameSite: "strict", maxAge: 86400 } }); ``` -------------------------------- ### Namespace Introduction and Usage Source: https://socket.io/pt-br/docs/v4/namespaces Demonstrates how to set up and use namespaces for different application modules like orders and users, including event handling and room management. ```APIDOC ## Namespaces A Namespace is a communication channel that allows you to split the logic of your application over a single shared connection (also called "multiplexing"). ### Introduction Each namespace has its own: * event handlers ```javascript io.of("/orders").on("connection", (socket) => { socket.on("order:list", () => {}); socket.on("order:create", () => {}); }); io.of("/users").on("connection", (socket) => { socket.on("user:list", () => {}); }); ``` * rooms ```javascript const orderNamespace = io.of("/orders"); orderNamespace.on("connection", (socket) => { socket.join("room1"); orderNamespace.to("room1").emit("hello"); }); const userNamespace = io.of("/users"); userNamespace.on("connection", (socket) => { socket.join("room1"); // distinct from the room in the "orders" namespace userNamespace.to("room1").emit("holà"); }); ``` * middlewares ```javascript const orderNamespace = io.of("/orders"); orderNamespace.use((socket, next) => { // ensure the socket has access to the "orders" namespace, and then next(); }); const userNamespace = io.of("/users"); userNamespace.use((socket, next) => { // ensure the socket has access to the "users" namespace, and then next(); }); ``` ### Possible Use Cases * Special namespace for authorized users: ```javascript const adminNamespace = io.of("/admin"); adminNamespace.use((socket, next) => { // ensure the user has sufficient rights next(); }); adminNamespace.on("connection", socket => { socket.on("delete user", () => { // ... }); }); ``` * Dynamically create namespaces per tenant: ```javascript const workspaces = io.of(/^\/\w+$/); workspaces.on("connection", socket => { const workspace = socket.nsp; workspace.emit("hello"); }); ``` ``` -------------------------------- ### Connect Socket.IO with Custom Options Source: https://socket.io/pt-br/docs/v4/client-api Illustrates how to establish a Socket.IO connection with advanced options, including specifying a namespace, setting reconnection delays, authentication tokens, and query parameters. It also shows the equivalent using the Manager class. ```javascript import { io } from "socket.io-client"; const socket = io("ws://example.com/my-namespace", { reconnectionDelayMax: 10000, auth: { token: "123" }, query: { "my-key": "my-value" } }); ``` ```javascript import { Manager } from "socket.io-client"; const manager = new Manager("ws://example.com", { reconnectionDelayMax: 10000, query: { "my-key": "my-value" } }); const socket = manager.socket("/my-namespace", { auth: { token: "123" } }); ``` -------------------------------- ### Initialize Socket.IO with Redis Adapter (redis@4+) Source: https://socket.io/pt-br/docs/v4/redis-adapter Sets up a Socket.IO server with the Redis adapter using redis@4 or later. It requires connecting both the publisher and subscriber Redis clients before attaching the adapter. ```javascript import { Server } from "socket.io"; import { createAdapter } from "@socket.io/redis-adapter"; import { createClient } from "redis"; const io = new Server(); const pubClient = createClient({ url: "redis://localhost:6379" }); const subClient = pubClient.duplicate(); Promise.all([pubClient.connect(), subClient.connect()]).then(() => { io.adapter(createAdapter(pubClient, subClient)); io.listen(3000); }); ``` -------------------------------- ### Client Initialization for Namespaces (Cross-Origin/Node.js) Source: https://socket.io/pt-br/docs/v4/namespaces Shows how to initialize client connections to different namespaces when the client and server are on different origins or when using Node.js. It includes specifying the server URL along with the namespace. ```javascript const socket = io("https://example.com"); // or io("https://example.com/" ), the main namespace const orderSocket = io("https://example.com/orders"); // the "orders" namespace const userSocket = io("https://example.com/users"); // the "users" namespace ``` -------------------------------- ### Initialize Socket.IO Client with io() Source: https://socket.io/pt-br/docs/v4/client-api Demonstrates how to initialize the Socket.IO client using the io() method. This can be done via a script tag, ESM import, or import maps. It shows basic connection to a local server and connection to a CDN. ```html ``` ```html ``` ```html ``` -------------------------------- ### MongoDB Emitter Usage Source: https://socket.io/pt-br/docs/v4/mongo-adapter Example of using the MongoDB emitter to send packets from a separate Node.js process. ```APIDOC ### Usage ### Description This example demonstrates how to use the MongoDB emitter to send messages to Socket.IO clients from a different Node.js process. It connects to MongoDB and then uses the emitter to broadcast a 'ping' event periodically. ### Method `Emitter.emit()` ### Endpoint N/A (Process-to-process communication) ### Parameters #### Request Body N/A ### Request Example ```javascript const { Emitter } = require("@socket.io/mongo-emitter"); const { MongoClient } = require("mongodb"); const mongoClient = new MongoClient("mongodb://localhost:27017/?replicaSet=rs0"); const main = async () => { await mongoClient.connect(); const mongoCollection = mongoClient.db("mydb").collection("socket.io-adapter-events"); const emitter = new Emitter(mongoCollection); setInterval(() => { emitter.emit("ping", new Date()); }, 1000); } main(); ``` ### Response N/A (Asynchronous emission) ``` -------------------------------- ### Migrate from socket.io-redis to @socket.io/redis-adapter Source: https://socket.io/pt-br/docs/v4/redis-adapter Demonstrates the migration from the older 'socket.io-redis' package to the newer '@socket.io/redis-adapter'. The key change is manually creating and providing Redis client instances. ```javascript const redisAdapter = require("socket.io-redis"); io.adapter(redisAdapter({ host: "localhost", port: 6379 })); ``` ```javascript const { createClient } = require("redis"); const { createAdapter } = require("@socket.io/redis-adapter"); const pubClient = createClient({ url: "redis://localhost:6379" }); const subClient = pubClient.duplicate(); io.adapter(createAdapter(pubClient, subClient)); ``` -------------------------------- ### Configuration: Redis Adapter Initialization Source: https://socket.io/pt-br/docs/v4/redis-adapter How to initialize the Socket.IO server with the Redis adapter using standard Redis clients. ```APIDOC ## SETUP Redis Adapter ### Description Initializes the Socket.IO server with a Redis adapter to enable cross-server event broadcasting. ### Method N/A (Library Configuration) ### Parameters #### Options - **key** (string) - Optional - The prefix for the name of the Pub/Sub channel. Default: "socket.io" - **requestsTimeout** (number) - Optional - Timeout for inter-server requests like fetchSockets(). Default: 5000 ### Request Example ```javascript import { Server } from "socket.io"; import { createAdapter } from "@socket.io/redis-adapter"; import { createClient } from "redis"; const io = new Server(); const pubClient = createClient({ url: "redis://localhost:6379" }); const subClient = pubClient.duplicate(); Promise.all([pubClient.connect(), subClient.connect()]).then(() => { io.adapter(createAdapter(pubClient, subClient)); io.listen(3000); }); ``` ``` -------------------------------- ### Client Initialization with Namespaces Source: https://socket.io/pt-br/docs/v4/namespaces Shows how to initialize Socket.IO clients to connect to the main namespace or custom namespaces, both same-origin and cross-origin. ```APIDOC ## Client initialization Same-origin version: ```javascript const socket = io(); // or io("/"", the main namespace const orderSocket = io("/orders"); // the "orders" namespace const userSocket = io("/users"); // the "users" namespace ``` Cross-origin/Node.js version: ```javascript const socket = io("https://example.com"); // or io("https://example.com/"", the main namespace const orderSocket = io("https://example.com/orders"); // the "orders" namespace const userSocket = io("https://example.com/users"); // the "users" namespace ``` In the example above, only one WebSocket connection will be established, and the packets will automatically be routed to the right namespace. Please note that multiplexing will be disabled in the following cases: * multiple creation for the same namespace ```javascript const socket1 = io(); const socket2 = io(); // no multiplexing, two distinct WebSocket connections ``` * different domains ```javascript const socket1 = io("https://first.example.com"); const socket2 = io("https://second.example.com"); // no multiplexing, two distinct WebSocket connections ``` * usage of the forceNew option ```javascript const socket1 = io(); const socket2 = io("/admin", { forceNew: true }); // no multiplexing, two distinct WebSocket connections ``` ``` -------------------------------- ### Get Socket ID Source: https://socket.io/pt-br/docs/v4/client-api Retrieves the unique identifier for the current socket session. The 'socket.id' property is set after the 'connect' event is fired. ```javascript const socket = io("http://localhost"); console.log(socket.id); // undefined initially socket.on("connect", () => { console.log(socket.id); // e.g., "G5p5..." }); ``` -------------------------------- ### IO Client Initialization Source: https://socket.io/pt-br/docs/v4/client-api Demonstrates various ways to initialize the Socket.IO client, including script tags, ESM imports, and Node.js/React Native environments. ```APIDOC ## IO Client Initialization ### Description Examples of how to include and initialize the Socket.IO client library in different environments. ### Usage #### Script Tag ```html ``` #### ESM Import ```html ``` #### Import Map ```html ``` #### Node.js / React Native (CommonJS & ESM) ```javascript // ESM syntax import { io } from "socket.io-client"; // CommonJS syntax const { io } = require("socket.io-client"); ``` ``` -------------------------------- ### Server Initialization Configuration Source: https://socket.io/pt-br/docs/v4/server-options Configuration options for the Socket.IO server instance, including path customization and adapter integration. ```APIDOC ## Server Configuration Options ### Description Configures the behavior of the Socket.IO server instance during initialization. ### Parameters #### Configuration Object - **path** (string) - Optional - The name of the path to capture on the server. Defaults to `/socket.io/`. - **serveClient** (boolean) - Optional - Whether to serve the client files. Defaults to `true`. - **adapter** (object) - Optional - The adapter to use for cross-server communication. Defaults to `socket.io-adapter`. - **connectTimeout** (number) - Optional - Milliseconds before disconnecting a client that hasn't joined a namespace. Defaults to `45000`. - **pingTimeout** (number) - Optional - Milliseconds to wait for a pong response. Defaults to `20000`. - **pingInterval** (number) - Optional - Milliseconds between pings. Defaults to `25000`. - **maxHttpBufferSize** (number) - Optional - Maximum bytes for a single message. Defaults to `1e6` (1 MB). ### Request Example ```javascript const io = new Server(httpServer, { path: "/my-custom-path/", pingTimeout: 30000, maxHttpBufferSize: 1e8 }); ``` ``` -------------------------------- ### Handling Disconnect Event in Socket.IO Server Source: https://socket.io/pt-br/docs/v4/tutorial/step-3 Extends the basic Socket.IO server setup to log when a user disconnects. This is useful for managing client presence and resources. ```javascript io.on('connection', (socket) => { console.log('a user connected'); socket.on('disconnect', () => { console.log('user disconnected'); }); }); ``` -------------------------------- ### Registering Socket.IO Middleware Source: https://socket.io/pt-br/docs/v4/middlewares Demonstrates how to register a middleware function using io.use. The function receives the socket instance and a next callback to proceed or reject the connection. ```javascript io.use((socket, next) => { if (isValid(socket.request)) { next(); } else { next(new Error("invalid")); } }); ``` -------------------------------- ### socket.prependAny Source: https://socket.io/pt-br/docs/v4/client-api Adds a "catch-all" listener to the beginning of the listeners array. ```APIDOC ## socket.prependAny(callback) ### Description Adds a "catch-all" listener to the beginning of the array of listeners for any event. This listener will be invoked before any other `onAny` listeners. ### Method `socket.prependAny` ### Parameters - **callback** (Function) - The function to execute for any event. It receives the event name and arguments. ### Request Example ```javascript socket.prependAny((event, ...args) => { console.log(`Prepended listener caught: ${event}`); }); ``` ### Returns `` - The socket instance for chaining. ``` -------------------------------- ### Initialize Socket.IO with Redis Adapter (redis@3) Source: https://socket.io/pt-br/docs/v4/redis-adapter Configures a Socket.IO server with the Redis adapter for older versions of the redis package (v3). Connection to Redis clients is handled automatically, so explicit connect() calls are not needed. ```javascript import { Server } from "socket.io"; import { createAdapter } from "@socket.io/redis-adapter"; import { createClient } from "redis"; const io = new Server(); const pubClient = createClient({ url: "redis://localhost:6379" }); const subClient = pubClient.duplicate(); io.adapter(createAdapter(pubClient, subClient)); io.listen(3000); ``` -------------------------------- ### Initialize Socket.IO Manager Source: https://socket.io/pt-br/docs/v4/client-api Demonstrates how to create a Socket.IO Manager instance, which handles the underlying Engine.IO client and connection logic, including reconnections. A single Manager can be used for multiple Sockets across different namespaces. ```javascript import { Manager } from "socket.io-client"; const manager = new Manager("https://example.com"); const socket = manager.socket("/"); // namespace principal const adminSocket = manager.socket("/admin"); // namespace "admin" ``` -------------------------------- ### Manage Socket.IO Rooms Source: https://socket.io/pt-br/docs/v4/rooms Demonstrates how to join a room, broadcast to a single room, broadcast to multiple rooms, and broadcast to a room excluding the sender. ```javascript io.on("connection", (socket) => { socket.join("some room"); }); io.to("some room").emit("some event"); io.to("room1").to("room2").to("room3").emit("some event"); io.on("connection", (socket) => { socket.to("some room").emit("some event"); }); ``` -------------------------------- ### Registering a Middleware Source: https://socket.io/pt-br/docs/v4/middlewares Demonstrates how to register a middleware function using `io.use()`. The middleware can validate incoming connections and decide whether to proceed or reject them by calling `next()` or `next(new Error())`. ```APIDOC ## Registering a Middleware A middleware function has access to the Socket instance and to the next registered middleware function. ### Method ```javascript io.use((socket, next) => { if (isValid(socket.request)) { next(); } else { next(new Error("invalid")); } }); ``` You can register several middleware functions, and they will be executed sequentially. ### Method ```javascript io.use((socket, next) => { next(); }); io.use((socket, next) => { next(new Error("thou shall not pass")); }); io.use((socket, next) => { // not executed, since the previous middleware has returned an error next(); }); ``` **Important note**: Ensure `next()` is called in all cases to prevent connections from hanging. The Socket instance is not fully connected when middleware executes. ``` -------------------------------- ### Main Namespace and Custom Namespaces Source: https://socket.io/pt-br/docs/v4/namespaces Explains the default main namespace ('/') and how to create and use custom namespaces on the server and client sides. ```APIDOC ## Main namespace Until now, you interacted with the main namespace, called `/`. The `io` instance inherits all of its methods: ```javascript io.on("connection", (socket) => {}); io.use((socket, next) => { next() }); io.emit("hello"); // are actually equivalent to io.of("/").on("connection", (socket) => {}); io.of("/").use((socket, next) => { next() }); io.of("/").emit("hello"); ``` Some tutorials may also mention `io.sockets`, it's simply an alias for `io.of("/")`. ```javascript io.sockets === io.of("/") ``` ## Custom namespaces To set up a custom namespace, you can call the `of` function on the server-side: ```javascript const nsp = io.of("/my-namespace"); nsp.on("connection", socket => { console.log("someone connected"); }); nsp.emit("hi", "everyone!"); ``` ``` -------------------------------- ### Configurar Adaptador Redis para Socket.IO Source: https://socket.io/pt-br/docs/v4/server-options Implementa o adaptador Redis para permitir a comunicação entre múltiplos nós do servidor Socket.IO. O exemplo demonstra a configuração usando clientes Redis para publicação e subscrição. ```javascript const { Server } = require("socket.io"); const { createAdapter } = require("@socket.io/redis-adapter"); const { createClient } = require("redis"); const pubClient = createClient({ host: "localhost", port: 6379 }); const subClient = pubClient.duplicate(); const io = new Server({ adapter: createAdapter(pubClient, subClient) }); io.listen(3000); ``` ```typescript import { Server } from "socket.io"; import { createAdapter } from "@socket.io/redis-adapter"; import { createClient } from "redis"; const pubClient = createClient({ host: "localhost", port: 6379 }); const subClient = pubClient.duplicate(); const io = new Server({ adapter: createAdapter(pubClient, subClient) }); io.listen(3000); ``` -------------------------------- ### io() Method Source: https://socket.io/pt-br/docs/v4/client-api Explains the `io()` method for creating Socket.IO client instances, including parameters and options. ```APIDOC ## io([url][, options]) ### Description Creates a new Manager for the given URL and attempts to reuse an existing Manager for subsequent calls, unless the `multiplex` option is passed as `false`. This is equivalent to passing `"force new connection": true` or `forceNew: true`. A new `Socket` instance is returned for the Namespace specified by the URL's pathname, defaulting to `/`. Query parameters can also be provided, either with a `query` option or by directing to the URL (e.g., `http://localhost/users?token=abc`). ### Parameters * **url** `` (default to `window.location`) * **options** `` * **forceNew** `` - If you want to create a new connection. * **reconnectionDelayMax** `` - Maximum delay between reconnections. * **auth** `` - Authentication credentials. * **token** `` - Authentication token. * **query** `` - Custom query parameters. ### Returns * `` ### Request Example ```javascript import { io } from "socket.io-client"; const socket = io("ws://example.com/my-namespace", { reconnectionDelayMax: 10000, auth: { token: "123" }, query: { "my-key": "my-value" } }); ``` ### Equivalent Manager Initialization ```javascript import { Manager } from "socket.io-client"; const manager = new Manager("ws://example.com", { reconnectionDelayMax: 10000, query: { "my-key": "my-value" } }); const socket = manager.socket("/my-namespace", { auth: { token: "123" } }); ``` ``` -------------------------------- ### Server Configuration Options Source: https://socket.io/pt-br/docs/v4/server-options Configuration settings for the Socket.IO server instance. ```APIDOC ## Server Configuration Options ### Description Configure the behavior of the Socket.IO server during initialization. ### Parameters - **allowRequest** (Function) - Optional - A function that receives a handshake request and decides whether to continue. - **transports** (Array) - Optional - Allowed low-level transports (default: ["polling", "websocket"]). - **allowUpgrades** (Boolean) - Optional - Whether to allow transport upgrades (default: true). - **perMessageDeflate** (Object|Boolean) - Optional - Configuration for the WebSocket permessage-deflate extension (default: false). - **httpCompression** (Object|Boolean) - Optional - Configuration for HTTP long-polling compression (default: true). - **wsEngine** (Object) - Optional - The WebSocket server implementation to use (default: require("ws").Server). ### Request Example ```javascript const io = new Server(httpServer, { allowRequest: (req, callback) => { callback(null, true); }, transports: ["websocket"], perMessageDeflate: { threshold: 2048 } }); ``` ``` -------------------------------- ### Socket.IO Client - Basic Connection (JavaScript) Source: https://socket.io/pt-br/docs/v4 Demonstrates a basic Socket.IO client connection. Note that this client will NOT be able to connect to a standard WebSocket server due to Socket.IO's additional metadata. ```javascript const socket = io("ws://echo.websocket.org"); ``` -------------------------------- ### Dynamically Creating Namespaces for Tenants (Node.js) Source: https://socket.io/pt-br/docs/v4/namespaces This snippet shows how to dynamically create namespaces using a regular expression, suitable for multi-tenant applications. Each tenant can have its own namespace, allowing for isolated communication. ```javascript const workspaces = io.of(/^\/\w+$/); workspaces.on("connection", socket => { const workspace = socket.nsp; workspace.emit("hello"); }); ``` -------------------------------- ### Initialize Redis Streams Adapter Source: https://socket.io/pt-br/docs/v4/redis-streams-adapter Configure a Socket.IO server to use the Redis Streams adapter. This involves creating a Redis client, connecting to the server, and passing the client to the adapter during server initialization. ```javascript import { createClient } from "redis"; import { Server } from "socket.io"; import { createAdapter } from "@socket.io/redis-streams-adapter"; const redisClient = createClient({ host: "localhost", port: 6379 }); await redisClient.connect(); const io = new Server({ adapter: createAdapter(redisClient) }); io.listen(3000); ``` -------------------------------- ### Listen for Socket.IO Room Creation and Join Events (JavaScript) Source: https://socket.io/pt-br/docs/v4/rooms This snippet demonstrates how to use the Socket.IO adapter to listen for 'create-room' and 'join-room' events. It logs messages to the console when a room is created or when a socket joins a room. This functionality requires Socket.IO version 3.1.0 or later. ```javascript io.of("/").adapter.on("create-room", (room) => { console.log(`room ${room} was created`); }); io.of("/").adapter.on("join-room", (room, id) => { console.log(`socket ${id} has joined room ${room}`); }); ``` -------------------------------- ### Listar Ouvintes de Todos os Eventos de Saída com Socket.IO Source: https://socket.io/pt-br/docs/v4/client-api Retorna a lista de ouvintes catch-all registrados para pacotes de saída. ```javascript const listeners = socket.listenersAnyOutgoing(); ``` -------------------------------- ### MongoDB Adapter Options Source: https://socket.io/pt-br/docs/v4/mongo-adapter Overview of configuration options available for the MongoDB adapter. ```APIDOC ## Options | Name | Description | Default value | Added in | |---|---|---|---| | `uid` | the ID of this node | a random id | `v0.1.0` | | `requestsTimeout` | the timeout for inter-server requests such as `fetchSockets()` or `serverSideEmit()` with ack | `5000` | `v0.1.0` | | `heartbeatInterval` | the number of ms between two heartbeats | `5000` | `v0.1.0` | | `heartbeatTimeout` | the number of ms without heartbeat before we consider a node down | `10000` | `v0.1.0` | | `addCreatedAtField` | whether to add a `createdAt` field to each MongoDB document | `false` | `v0.2.0` | ``` -------------------------------- ### Integrating Express Middleware Source: https://socket.io/pt-br/docs/v4/middlewares Demonstrates how to use Express-compatible middleware with the underlying Socket.IO engine, useful for sessions or security headers. ```javascript import helmet from "helmet"; io.engine.use(helmet()); ``` -------------------------------- ### Implementing Middlewares for Namespaces (Node.js) Source: https://socket.io/pt-br/docs/v4/namespaces Shows how to apply middleware functions to namespaces to perform checks or modifications before a socket connection is fully established. This is useful for authorization or authentication specific to a namespace. ```javascript const orderNamespace = io.of("/orders"); orderNamespace.use((socket, next) => { // ensure the socket has access to the "orders" namespace, and then next(); }); const userNamespace = io.of("/users"); userNamespace.use((socket, next) => { // ensure the socket has access to the "users" namespace, and then next(); }); ``` -------------------------------- ### Ouvir Todos os Eventos de Saída com Socket.IO Source: https://socket.io/pt-br/docs/v4/client-api Registra um ouvinte para todos os pacotes de saída. Útil para inspecionar ou modificar dados antes de serem enviados. ```javascript socket.onAnyOutgoing((event, ...args) => { console.log(`got ${event}`); }); ``` -------------------------------- ### Multiplexing Connections with Socket.IO Namespaces Source: https://socket.io/pt-br/docs/v4 Illustrates how to divide application logic into separate channels using Socket.IO namespaces. This allows for distinct handling of different types of users or functionalities, such as a general channel and an admin-only channel, all within a single shared connection. ```javascript io.on("connection", (socket) => { // classic users }); io.of("/admin").on("connection", (socket) => { // admin users }); ``` -------------------------------- ### Ouvir Todos os Eventos de Saída (Início) com Socket.IO Source: https://socket.io/pt-br/docs/v4/client-api Registra um ouvinte no início da lista de ouvintes para pacotes de saída. Garante que este ouvinte seja processado primeiro. ```javascript socket.prependAnyOutgoing((event, ...args) => { console.log(`got ${event}`); }); ``` -------------------------------- ### Ouvir Evento Único com Socket.IO Source: https://socket.io/pt-br/docs/v4/client-api Registra um manipulador que será invocado apenas uma vez para o evento especificado. Útil para ações que devem ocorrer apenas na primeira ocorrência de um evento. ```javascript socket.once("my-event", () => { // ... }); ``` -------------------------------- ### Client-Side Socket.IO Connection (ES5) Source: https://socket.io/pt-br/docs/v4/tutorial/step-3 Includes the Socket.IO client-side JavaScript library and establishes a connection to the server using ES5 syntax. Assumes the server is serving the client script. ```html ``` -------------------------------- ### Client-Side Socket.IO Connection (ES6) Source: https://socket.io/pt-br/docs/v4/tutorial/step-3 Includes the Socket.IO client-side JavaScript library and establishes a connection to the server. Assumes the server is serving the client script. ```html ``` -------------------------------- ### Create Socket for Namespace Source: https://socket.io/pt-br/docs/v4/client-api Creates a new Socket instance for a given namespace. Only the 'auth' option is considered; other options should be passed to the Manager constructor. ```javascript const manager = new Manager("https://example.com"); const socket = manager.socket("/my-namespace", { auth: { token: "123" } }); ``` -------------------------------- ### Configure MongoDB Adapter with TTL Index Source: https://socket.io/pt-br/docs/v4/mongo-adapter Sets up the Socket.IO server using a TTL index for event cleanup. This allows for time-based document expiration. ```javascript const { Server } = require("socket.io"); const { createAdapter } = require("@socket.io/mongo-adapter"); const { MongoClient } = require("mongodb"); const DB = "mydb"; const COLLECTION = "socket.io-adapter-events"; const io = new Server(); const mongoClient = new MongoClient("mongodb://localhost:27017/?replicaSet=rs0"); const main = async () => { await mongoClient.connect(); const mongoCollection = mongoClient.db(DB).collection(COLLECTION); await mongoCollection.createIndex( { createdAt: 1 }, { expireAfterSeconds: 3600, background: true } ); io.adapter(createAdapter(mongoCollection, { addCreatedAtField: true })); io.listen(3000); } main(); ``` -------------------------------- ### Configurar Caminho Personalizado do Socket.IO Source: https://socket.io/pt-br/docs/v4/server-options Define um caminho de endpoint personalizado para o servidor e cliente Socket.IO. É crucial que ambos os lados utilizem o mesmo valor para garantir a conexão. ```javascript import { createServer } from "http"; import { Server } from "socket.io"; const httpServer = createServer(); const io = new Server(httpServer, { path: "/my-custom-path/" }); ``` ```javascript import { io } from "socket.io-client"; const socket = io("https://example.com", { path: "/my-custom-path/" }); ``` -------------------------------- ### Defining and Handling Events in Namespaces (Node.js) Source: https://socket.io/pt-br/docs/v4/namespaces This snippet demonstrates how to define custom namespaces for 'orders' and 'users' and attach event listeners to sockets within those namespaces. It shows how to handle specific events like 'order:list', 'order:create', and 'user:list'. ```javascript io.of("/orders").on("connection", (socket) => { socket.on("order:list", () => {}); socket.on("order:create", () => {}); }); io.of("/users").on("connection", (socket) => { socket.on("user:list", () => {}); }); ``` -------------------------------- ### Securing a Namespace with Middleware (Node.js) Source: https://socket.io/pt-br/docs/v4/namespaces Demonstrates a use case for namespaces and middleware: creating a protected '/admin' namespace. The middleware ensures that only authorized users can connect to this namespace, separating sensitive operations. ```javascript const adminNamespace = io.of("/admin"); adminNamespace.use((socket, next) => { // ensure the user has sufficient rights next(); }); adminNamespace.on("connection", socket => { socket.on("delete user", () => { // ... }); }); ``` -------------------------------- ### Main Namespace Equivalents (Node.js) Source: https://socket.io/pt-br/docs/v4/namespaces Explains that the main namespace '/' can be accessed directly using `io` methods or explicitly via `io.of('/')`. It also clarifies that `io.sockets` is an alias for `io.of('/')`. ```javascript io.on("connection", (socket) => {}); io.use((socket, next) => { next() }); io.emit("hello"); // are actually equivalent to io.of("/").on("connection", (socket) => {}); io.of("/").use((socket, next) => { next() }); io.of("/").emit("hello"); io.sockets === io.of("/") ``` -------------------------------- ### Ouvir Todos os Eventos com Socket.IO Source: https://socket.io/pt-br/docs/v4/client-api Registra um ouvinte abrangente que é acionado para qualquer evento emitido. Útil para logging ou auditoria de eventos. ```javascript socket.onAny((event, ...args) => { console.log(`got ${event}`); }); ``` -------------------------------- ### Open Manager Connection with Callback Source: https://socket.io/pt-br/docs/v4/client-api Opens a new connection for the Manager. If autoConnect is false, this initiates a connection attempt. The callback function is optional and is executed upon connection success or failure. ```javascript import { Manager } from "socket.io-client"; const manager = new Manager("https://example.com", { autoConnect: false }); const socket = manager.socket("/"); manager.open((err) => { if (err) { // Ocorreu um erro } else { // a conexão foi estabelecida com sucesso } }); ``` -------------------------------- ### Validate Handshake Requests with allowRequest Source: https://socket.io/pt-br/docs/v4/server-options Demonstrates how to use the allowRequest option to validate incoming handshakes or upgrade requests. It shows both a basic validation check and an asynchronous approach for session management. ```javascript const io = new Server(httpServer, { allowRequest: (req, callback) => { const isOriginValid = check(req); callback(null, isOriginValid); } }); ``` ```javascript import { serialize } from "cookie"; const io = new Server(httpServer, { allowRequest: async (req, callback) => { const session = await fetchSession(req); req.session = session; callback(null, true); } }); io.engine.on("initial_headers", (headers, req) => { if (req.session) { headers["set-cookie"] = serialize("sid", req.session.id, { sameSite: "strict" }); } }); ``` -------------------------------- ### Emit and Listen for Socket Events Source: https://socket.io/pt-br/docs/v4/client-api Demonstrates emitting custom events with data to the server and listening for custom events from the server. The 'socket.emit' method sends data, while 'socket.on' registers a listener for incoming events. ```javascript socket.emit("hello", { a: "b", c: [] }); socket.on("hey", (...args) => { // ... handle incoming event }); ``` -------------------------------- ### Sending Credentials with Middleware Source: https://socket.io/pt-br/docs/v4/middlewares Explains how clients can send authentication credentials using the `auth` option, and how these credentials can be accessed on the server-side within the middleware's handshake object. ```APIDOC ## Sending Credentials The client can send credentials with the `auth` option: ### Client-side Example ```javascript // plain object const socket = io({ auth: { token: "abc" } }); // or with a function const socket = io({ auth: (cb) => { cb({ token: "abc" }); } }); ``` Those credentials can be accessed in the handshake object on the server-side: ### Server-side Example ```javascript io.use((socket, next) => { const token = socket.handshake.auth.token; // ... }); ``` ``` -------------------------------- ### socket.prependAnyOutgoing Source: https://socket.io/pt-br/docs/v4/client-api Adds a "catch-all" listener for outgoing events to the beginning of the listeners array. ```APIDOC ## socket.prependAnyOutgoing(callback) ### Description Adds a "catch-all" listener to the beginning of the array of listeners for any outgoing event. This listener will be invoked before any other `onAnyOutgoing` listeners. ### Method `socket.prependAnyOutgoing` ### Parameters - **callback** (Function) - The function to execute for any outgoing event. It receives the event name and arguments. ### Request Example ```javascript socket.prependAnyOutgoing((event, ...args) => { console.log(`Prepended outgoing listener caught: ${event}`); }); ``` ### Returns `` - The socket instance for chaining. ``` -------------------------------- ### Listar Ouvintes com Socket.IO Source: https://socket.io/pt-br/docs/v4/client-api Retorna um array contendo todos os ouvintes registrados para um evento específico. ```javascript socket.on("my-event", () => { // ... }); console.log(socket.listeners("my-event"));// prints [ [Function] ] ```