### 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** `