### Install Dependencies and Start Project
Source: https://github.com/socketio/socket.io/blob/main/examples/custom-parsers/README.md
Installs project dependencies and starts the application. This is a common first step before running Socket.IO examples.
```bash
$
npm i && npm start
```
--------------------------------
### Install and Run Socket.IO Connection State Recovery Example
Source: https://github.com/socketio/socket.io/blob/main/examples/connection-state-recovery-example/README.md
Instructions for setting up the example project. Choose either ES modules or CommonJS syntax. Ensure dependencies are installed before starting the server.
```shell
# choose your module syntax (either ES modules or CommonJS)
$ cd esm/
# install the dependencies
$ npm i
# start the server
$ node index.js
```
--------------------------------
### Install and Start Angular Frontend
Source: https://github.com/socketio/socket.io/blob/main/examples/basic-crud-application/README.md
Navigate to the Angular client directory, install dependencies, and start the development server.
```bash
cd angular-client
npm install
npm start
```
--------------------------------
### Install and Start TypeScript Server
Source: https://github.com/socketio/socket.io/blob/main/examples/basic-crud-application/README.md
Navigate to the server directory, install Node.js dependencies, and start the server.
```bash
cd server
npm install
npm start
```
--------------------------------
### Start Server
Source: https://github.com/socketio/socket.io/blob/main/examples/private-messaging/README.md
After installing dependencies, run this command to start the server.
```bash
npm start
```
--------------------------------
### Install and Start Project
Source: https://github.com/socketio/socket.io/blob/main/examples/whiteboard/README.md
Run this command to install dependencies and start the Socket.IO collaborative whiteboard server. Access the whiteboard via http://localhost:3000.
```bash
$ npm ci && npm start
```
--------------------------------
### Install, Build, and Start Socket.IO Server
Source: https://github.com/socketio/socket.io/blob/main/examples/webpack-build-server/README.md
Use these commands to install dependencies, build the project, and start the Socket.IO server.
```bash
npm i
npm run build
npm start
```
--------------------------------
### Install and Start Socket.IO Server
Source: https://github.com/socketio/socket.io/blob/main/examples/ReactNativeExample/README.md
Installs Node.js dependencies for the Socket.IO server and starts the server. Navigate to the 'server' directory before running these commands.
```bash
cd server
npm install
npm start
```
--------------------------------
### Start Server
Source: https://github.com/socketio/socket.io/blob/main/examples/nwjs-example/README.md
Start the Socket.IO server after installing dependencies.
```bash
# start the server
$ npm start
```
--------------------------------
### Install Dependencies and Run Server/Client
Source: https://github.com/socketio/socket.io/blob/main/examples/es-modules/README.md
Use these commands to set up and run the Socket.IO ES modules example. Ensure Node.js version is 12.17.0 or higher.
```bash
# install the dependencies
$ npm ci
# start the server
$ node server.js
# start the client
$ node client.js
```
--------------------------------
### Install and Start Socket.IO Chat
Source: https://github.com/socketio/socket.io/blob/main/examples/chat/README.md
Run these commands in your terminal to install dependencies and start the chat server. Point your browser to http://localhost:3000 to access the chat.
```bash
$ npm i
$ npm start
```
--------------------------------
### Start the Socket.IO Application
Source: https://github.com/socketio/socket.io/blob/main/examples/basic-crud-application/server-postgres-cluster/README.md
Launches the main application server. This command should be executed after dependencies are installed.
```bash
$ npm start
```
--------------------------------
### Start NW.js Client App
Source: https://github.com/socketio/socket.io/blob/main/examples/nwjs-example/README.md
Start your NW.js application after installing dependencies.
```bash
# start the app
$ nw .
```
--------------------------------
### Install Server Dependencies
Source: https://github.com/socketio/socket.io/blob/main/examples/nwjs-example/README.md
Navigate to the server directory and install its dependencies.
```bash
$ cd server
# install the dependencies
$ npm i
```
--------------------------------
### Start Docker Compose
Source: https://github.com/socketio/socket.io/blob/main/examples/cluster-haproxy/README.md
Use this command to launch the Socket.IO chat demo with HAProxy and Redis using Docker Compose. Ensure Docker Compose is installed.
```bash
docker-compose up -d
```
--------------------------------
### Install Dependencies
Source: https://github.com/socketio/socket.io/blob/main/examples/passport-example/README.md
Install the necessary dependencies for the project.
```bash
npm ci && npm start
```
--------------------------------
### Start Frontend Development Server
Source: https://github.com/socketio/socket.io/blob/main/examples/private-messaging/README.md
Execute this command to start the development server for the frontend.
```bash
npm run serve
```
--------------------------------
### Install Server Dependencies
Source: https://github.com/socketio/socket.io/blob/main/examples/private-messaging/README.md
Navigate to the server directory and run this command to install its dependencies.
```bash
cd server
npm install
```
--------------------------------
### Run Docker Compose
Source: https://github.com/socketio/socket.io/blob/main/examples/basic-crud-application/server-postgres-cluster/README.md
Starts the necessary Docker containers for the project. Ensure Docker is installed and running.
```bash
$ docker-compose up -d
```
--------------------------------
### Install @socket.io/cluster-adapter
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-cluster-adapter/README.md
Install the cluster adapter package using npm.
```bash
npm install @socket.io/cluster-adapter
```
--------------------------------
### Client Usage Example
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io/README.md
Example of how to integrate the Engine.IO client in an HTML file.
```APIDOC
## Client Usage Example
```html
```
```
--------------------------------
### Install Socket.IO with npm
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io/Readme.md
Install the socket.io package using npm.
```bash
npm install socket.io
```
--------------------------------
### Install Dependencies
Source: https://github.com/socketio/socket.io/blob/main/examples/webtransport/README.md
Run this command to install the necessary Node.js dependencies for the project.
```shell
# install dependencies
$ npm i
```
--------------------------------
### Install Socket.IO with yarn
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io/Readme.md
Install the socket.io package using yarn.
```bash
yarn add socket.io
```
--------------------------------
### Install @socket.io/component-emitter
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-component-emitter/Readme.md
Install the package using npm.
```bash
$ npm i @socket.io/component-emitter
```
--------------------------------
### Start Socket.IO Server
Source: https://github.com/socketio/socket.io/blob/main/examples/angular-todomvc/README.md
Execute this command to launch the Socket.IO server for the project.
```bash
npm run start:server
```
--------------------------------
### Start Socket.IO Server
Source: https://github.com/socketio/socket.io/blob/main/examples/webtransport/README.md
Execute this command to start the Socket.IO server using Node.js.
```shell
# start the server
$ node index.js
```
--------------------------------
### Starting Socket.IO Server (1.0)
Source: https://github.com/socketio/socket.io/wiki/Migrating-to-1.0
Shows the current method for initializing a Socket.IO server instance with options.
```javascript
var io = require('socket.io');
var socket = io({ /* options */ });
```
--------------------------------
### Start the Server
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io/examples/latency/README.md
Execute this command to start the eio-latency server. Access the application via your browser at localhost:3000 or the specified PORT environment variable.
```bash
$ node index
```
--------------------------------
### Start Nuxt Development Server
Source: https://github.com/socketio/socket.io/blob/main/examples/nuxt-example/README.md
Start the Nuxt development server on http://localhost:3000 using various package managers.
```bash
# npm
npm run dev
# pnpm
pnpm dev
# yarn
yarn dev
# bun
bun run dev
```
--------------------------------
### Install @socket.io/postgres-emitter
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-postgres-emitter/README.md
Install the package and its peer dependency 'pg' using npm.
```bash
npm install @socket.io/postgres-emitter pg
```
--------------------------------
### Install Engine.IO Client with npm
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io-client/README.md
Install the engine.io-client package using npm for use with browserify.
```bash
$ npm install engine.io-client
```
--------------------------------
### Start Socket.IO Server
Source: https://github.com/socketio/socket.io/blob/main/examples/create-react-app-example/README.md
This script is used to initiate the Socket.IO server process for the project.
```bash
yarn start-server
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/socketio/socket.io/blob/main/examples/basic-crud-application/server-postgres-cluster/README.md
Installs all required Node.js packages for the project. This should be run after cloning the repository.
```bash
$ npm install
```
--------------------------------
### Run Development Server
Source: https://github.com/socketio/socket.io/blob/main/examples/nextjs-app-router/README.md
Use one of these commands to start the Next.js development server. Open http://localhost:3000 in your browser to view the application.
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
--------------------------------
### Server Usage Examples
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io/README.md
Demonstrates different ways to integrate and use the Engine.IO server.
```APIDOC
## Server Usage Examples
### (A) Listening on a port
```js
const engine = require('engine.io');
const server = engine.listen(80);
server.on('connection', socket => {
socket.send('utf 8 string');
socket.send(Buffer.from([0, 1, 2, 3, 4, 5])); // binary data
});
```
### (B) Intercepting requests for a http.Server
```js
const engine = require('engine.io');
const http = require('http').createServer().listen(3000);
const server = engine.attach(http);
server.on('connection', socket => {
socket.on('message', data => { });
socket.on('close', () => { });
});
```
### (C) Passing in requests
```js
const engine = require('engine.io');
const server = new engine.Server();
server.on('connection', socket => {
socket.send('hi');
});
// …
httpServer.on('upgrade', (req, socket, head) => {
server.handleUpgrade(req, socket, head);
});
httpServer.on('request', (req, res) => {
server.handleRequest(req, res);
});
```
```
--------------------------------
### Run Server and Client Scripts
Source: https://github.com/socketio/socket.io/blob/main/examples/cluster-engine-node-cluster/README.md
Use these commands to run the server and client applications for the cluster example.
```bash
# run the server
$ node server.js
```
```bash
# run the client
$ node client.js
```
--------------------------------
### Install Dependencies with npm ci
Source: https://github.com/socketio/socket.io/blob/main/CONTRIBUTING.md
Installs all project dependencies using npm ci. Ensure Node.js 18+ and npm 7+ are installed.
```bash
npm ci
```
--------------------------------
### Install Dependencies
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io-client/README.md
Install project dependencies after cloning the repository. This is a prerequisite for running tests and development.
```bash
cd engine.io-client
npm install
```
--------------------------------
### Install and Build Socket.IO with npm
Source: https://github.com/socketio/socket.io/blob/main/examples/webpack-build/README.md
Use these npm commands to install dependencies and build the Socket.IO Webpack project.
```bash
$ npm i
$ npm run build
```
--------------------------------
### Install Project Dependencies with Yarn
Source: https://github.com/socketio/socket.io/blob/main/examples/basic-crud-application/vue-client/README.md
Run this command to install all necessary project dependencies using Yarn.
```bash
yarn install
```
--------------------------------
### Run Nest.js Application
Source: https://github.com/socketio/socket.io/blob/main/examples/nestjs-example/README.md
Commands to start the Nest.js application in different modes. Use 'start:dev' for development with hot-reloading and 'start:prod' for a production build.
```bash
npm run start
```
```bash
# watch mode
$ npm run start:dev
```
```bash
# production mode
$ npm run start:prod
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/socketio/socket.io/blob/main/examples/nestjs-example/README.md
Run this command in your project's root directory to install all necessary Node.js dependencies.
```bash
npm install
```
--------------------------------
### Install Socket.IO Cluster Engine
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-cluster-engine/README.md
Install the @socket.io/cluster-engine package using npm.
```bash
npm i @socket.io/cluster-engine
```
--------------------------------
### Start PostgreSQL Server
Source: https://github.com/socketio/socket.io/blob/main/examples/postgres-adapter-example/README.md
Use this command to start the PostgreSQL server in detached mode.
```bash
# start the postgres server
$ docker compose up -d
```
--------------------------------
### Install Client Dependencies
Source: https://github.com/socketio/socket.io/blob/main/examples/nwjs-example/README.md
Install the necessary dependencies for the Socket.IO client in your NW.js application.
```bash
# install the dependencies
$ npm i
```
--------------------------------
### Install Engine.IO Parser
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io-parser/Readme.md
Command to install the engine.io-parser package using npm.
```shell
npm install engine.io-parser
```
--------------------------------
### Run Socket.IO Client
Source: https://github.com/socketio/socket.io/blob/main/examples/postgres-adapter-example/README.md
Use this command to start a client that connects to the Socket.IO cluster.
```bash
# run the client
$ node client.js
```
--------------------------------
### Install Dependencies with Package Managers
Source: https://github.com/socketio/socket.io/blob/main/examples/nuxt-example/README.md
Install project dependencies using npm, pnpm, yarn, or bun.
```bash
# npm
npm install
# pnpm
pnpm install
# yarn
yarn install
# bun
bun install
```
--------------------------------
### Installing Socket.IO Redis Adapter
Source: https://github.com/socketio/socket.io/wiki/Migrating-to-1.0
Instructions for installing the `socket.io-redis` module using npm, which is required for using Redis as a Socket.IO adapter in version 1.0.
```bash
npm install socket.io-redis --save
```
--------------------------------
### Install Socket.IO Redis Streams Emitter and Redis
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-redis-streams-emitter/README.md
Install the necessary packages for using the Redis Streams emitter with Socket.IO.
```bash
npm install @socket.io/redis-streams-emitter redis
```
--------------------------------
### Compile and Hot-Reload for Development
Source: https://github.com/socketio/socket.io/blob/main/examples/basic-crud-application/vue-client/README.md
Use this command to start the development server, which compiles the project and enables hot-reloading for rapid development.
```bash
yarn serve
```
--------------------------------
### Setup Socket.IO Cluster Adapter in Node.js
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-cluster-adapter/README.md
This code demonstrates how to set up a Socket.IO server with the cluster adapter for broadcasting across multiple Node.js cluster workers. It includes setup for sticky sessions and primary/worker communication.
```javascript
const cluster = require("cluster");
const http = require("http");
const { Server } = require("socket.io");
const numCPUs = require("os").cpus().length;
const { setupMaster, setupWorker } = require("@socket.io/sticky");
const { createAdapter, setupPrimary } = require("@socket.io/cluster-adapter");
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
const httpServer = http.createServer();
// setup sticky sessions
setupMaster(httpServer, {
loadBalancingMethod: "least-connection",
});
// setup connections between the workers
setupPrimary();
// needed for packets containing buffers (you can ignore it if you only send plaintext objects)
// Node.js < 16.0.0
cluster.setupMaster({
serialization: "advanced",
});
// Node.js > 16.0.0
// cluster.setupPrimary({
// serialization: "advanced",
// });
httpServer.listen(3000);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on("exit", (worker) => {
console.log(`Worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
console.log(`Worker ${process.pid} started`);
const httpServer = http.createServer();
const io = new Server(httpServer);
// use the cluster adapter
io.adapter(createAdapter());
// setup connection with the primary process
setupWorker(io);
io.on("connection", (socket) => {
/* ... */
});
}
```
--------------------------------
### Connect to Socket.IO Server with Client Options
Source: https://github.com/socketio/socket.io/wiki/Configuring-Socket.IO
Establish a connection to a Socket.IO server from the client, specifying various connection options such as resource path, timeouts, and reconnection behavior. This example shows how to initiate a connection with custom settings.
```javascript
var socket = io.connect('http://server.com', {
// options here
});
```
--------------------------------
### Start Engine.IO Server on a Port
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io/README.md
Use this to start a new Engine.IO server listening on a specific port. It handles incoming connections and allows sending string or binary data.
```javascript
const engine = require('engine.io');
const server = engine.listen(80);
server.on('connection', socket => {
socket.send('utf 8 string');
socket.send(Buffer.from([0, 1, 2, 3, 4, 5])); // binary data
});
```
--------------------------------
### Run Development Server with npm
Source: https://github.com/socketio/socket.io/blob/main/examples/nextjs-pages-router/README.md
Use this command to start the Next.js development server using npm. The server will automatically reload as you edit files.
```bash
npm run dev
```
--------------------------------
### Run Socket.IO Cluster
Source: https://github.com/socketio/socket.io/blob/main/examples/postgres-adapter-example/README.md
Execute this command to start the Socket.IO cluster using the PostgreSQL adapter.
```bash
# run the cluster
$ node cluster.js
```
--------------------------------
### Run Development Server with Bun
Source: https://github.com/socketio/socket.io/blob/main/examples/nextjs-pages-router/README.md
Use this command to start the Next.js development server using Bun. The server will automatically reload as you edit files.
```bash
bun dev
```
--------------------------------
### Install Conventional Changelog CLI
Source: https://github.com/socketio/socket.io/blob/main/CONTRIBUTING.md
Installs the `conventional-changelog-cli` globally, which is required for generating changelogs based on commit messages.
```bash
npm i -g conventional-changelog-cli
```
--------------------------------
### Start Metro Server
Source: https://github.com/socketio/socket.io/blob/main/examples/ReactNativeExample/README.md
Starts the Metro JavaScript bundler for React Native development. Ensure you are in the root of your React Native project.
```bash
# using npm
npm start
# OR using Yarn
yarn start
```
--------------------------------
### Start Redis Server with Docker Compose
Source: https://github.com/socketio/socket.io/blob/main/examples/cluster-engine-redis/README.md
Use this command to start the Redis server in detached mode using Docker Compose.
```bash
docker compose up -d
```
--------------------------------
### Configuring Socket.IO Redis Adapter
Source: https://github.com/socketio/socket.io/wiki/Migrating-to-1.0
Example of how to configure Socket.IO to use the Redis adapter by specifying host and port.
```javascript
var redis = require('socket.io-redis');
io.adapter(redis({
host: 'localhost',
port: 6379
}));
```
--------------------------------
### Install Engine.IO Dependencies
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io/README.md
After cloning the Engine.IO repository, install the necessary Node.js dependencies using npm. This is required before running tests or development tasks.
```bash
cd engine.io
npm install
```
--------------------------------
### Run Socket.IO Server
Source: https://github.com/socketio/socket.io/blob/main/examples/cluster-engine-redis/README.md
Execute the Node.js server script to start the Socket.IO application.
```bash
node server.js
```
--------------------------------
### Start Development Server
Source: https://github.com/socketio/socket.io/blob/main/examples/create-react-app-example/README.md
Runs the React app in development mode, opening it at http://localhost:3000. The page auto-reloads on edits and displays lint errors in the console.
```bash
yarn start
```
--------------------------------
### Run Development Server with pnpm
Source: https://github.com/socketio/socket.io/blob/main/examples/nextjs-pages-router/README.md
Use this command to start the Next.js development server using pnpm. The server will automatically reload as you edit files.
```bash
pnpm dev
```
--------------------------------
### Run Development Server with Yarn
Source: https://github.com/socketio/socket.io/blob/main/examples/nextjs-pages-router/README.md
Use this command to start the Next.js development server using Yarn. The server will automatically reload as you edit files.
```bash
yarn dev
```
--------------------------------
### Instantiate Engine.IO Server
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io/README.md
Use the `require('engine.io')()` call to get a new Server instance. This can be attached to an existing http.Server or used with custom options.
```javascript
const httpServer;
// create a server first, and then attach
const eioServer = require('engine.io').Server();
eioServer.attach(httpServer);
// or call the module as a function to get `Server`
const eioServer = require('engine.io')();
eioServer.attach(httpServer);
// immediately attach
const eioServer = require('engine.io')(httpServer);
// with custom options
const eioServer = require('engine.io')(httpServer, {
maxHttpBufferSize: 1e3
});
```
--------------------------------
### Basic Usage of Postgres Emitter
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-postgres-emitter/README.md
Initialize the Emitter with a pg.Pool and emit events. This example emits a 'ping' event every second.
```javascript
const { Emitter } = require("@socket.io/postgres-emitter");
const { Pool } = require("pg");
const pool = new Pool({
user: "postgres",
host: "localhost",
database: "postgres",
password: "changeit",
port: 5432,
});
const io = new Emitter(pool);
setInterval(() => {
io.emit("ping", new Date());
}, 1000);
```
--------------------------------
### Run Socket.IO Test Suite
Source: https://github.com/socketio/socket.io/wiki/Contributing
Execute this command to run the unit test suite. Ensure Redis is installed and running on the default port, as it's required for testing the RedisStore backend.
```bash
make test
```
--------------------------------
### Run Angular Development Server
Source: https://github.com/socketio/socket.io/blob/main/examples/angular-todomvc/README.md
Use this command to start the Angular development server. The app will auto-reload on source file changes. Navigate to http://localhost:4200/.
```bash
ng serve
```
--------------------------------
### Get Angular CLI Help
Source: https://github.com/socketio/socket.io/blob/main/examples/angular-todomvc/README.md
Displays help information for the Angular CLI or specific commands. Refer to the Angular CLI Overview and Command Reference for more details.
```bash
ng help
```
--------------------------------
### Run Browser Tests
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io-parser/Readme.md
Command to execute the project's browser tests, typically requiring a setup like Sauce Labs via zuul.
```bash
npm run test:browser
```
--------------------------------
### Emitter Initialization
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-component-emitter/Readme.md
Demonstrates how to initialize the Emitter as an instance, a mixin for an object, or a prototype mixin.
```APIDOC
## Emitter(obj)
### Description
The `Emitter` may also be used as a mixin. For example a "plain" object may become an emitter, or you may extend an existing prototype.
### Method
Constructor / Mixin Function
### Endpoint
N/A (Class/Function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
As an `Emitter` instance:
```javascript
import { Emitter } from '@socket.io/component-emitter';
var emitter = new Emitter;
emitter.emit('something');
```
As a mixin:
```javascript
import { Emitter } from '@socket.io/component-emitter';
var user = { name: 'tobi' };
Emitter(user);
user.emit('im a user');
```
As a prototype mixin:
```javascript
import { Emitter } from '@socket.io/component-emitter';
Emitter(User.prototype);
```
### Response
N/A
```
--------------------------------
### Server Constructor and Options
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io/README.md
Initializes a new Socket.IO server instance with various configuration options.
```APIDOC
## Server Constructor
### Description
Initializes the server with optional configuration settings.
### Method
`constructor(options?: Object)`
### Parameters
#### Options
- **pingTimeout** (Number) - Optional - How many ms without a pong packet to consider the connection closed (default: `20000`).
- **pingInterval** (Number) - Optional - How many ms before sending a new ping packet (default: `25000`).
- **upgradeTimeout** (Number) - Optional - How many ms before an uncompleted transport upgrade is cancelled (default: `10000`).
- **maxHttpBufferSize** (Number) - Optional - Maximum bytes or characters a message can be before closing the session (default: `1E6`).
- **allowRequest** (Function) - Optional - A function to decide whether to continue a given handshake or upgrade request. It receives the request and a callback `fn(err, success)`.
- **transports** (Array) - Optional - Transports to allow connections to (default: `['polling', 'websocket']`).
- **allowUpgrades** (Boolean) - Optional - Whether to allow transport upgrades (default: `true`).
- **perMessageDeflate** (Object|Boolean) - Optional - Parameters for WebSocket permessage-deflate extension. Set to `true` to enable (default: `false`).
- **threshold** (Number) - Optional - Data is compressed only if its byte size is above this value (default: `1024`).
- **httpCompression** (Object|Boolean) - Optional - Parameters for HTTP compression for polling transports. Set to `false` to disable (default: `true`).
- **threshold** (Number) - Optional - Data is compressed only if its byte size is above this value (default: `1024`).
- **cookie** (Object|Boolean) - Optional - Configuration for the cookie containing the client sid for handshake response headers, potentially used for sticky-session (default: `false`). See [jshttp/cookie](https://github.com/jshttp/cookie#options-1) for supported options.
- **wsEngine** (Function) - Optional - WebSocket server implementation conforming to the `ws` interface. Default is `ws`.
- **cors** (Object) - Optional - Options forwarded to the `cors` module. See [expressjs/cors](https://github.com/expressjs/cors#configuration-options) for available options. Defaults to no CORS allowed.
- **initialPacket** (Object) - Optional - An optional packet to be concatenated to the handshake packet.
- **allowEIO3** (Boolean) - Optional - Whether to support v3 Engine.IO clients (default: `false`).
```
--------------------------------
### Server Instantiation
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io/README.md
Demonstrates different ways to instantiate a new Engine.IO Server instance, optionally attaching it to an existing HTTP server.
```APIDOC
## Server Instantiation
### Description
Returns a new `Server` instance. If the first argument is an `http.Server` then the new `Server` instance will be attached to it. Otherwise, the arguments are passed directly to the `Server` constructor.
### Parameters
- `http.Server`: optional, server to attach to.
- `Object`: optional, options object (see `Server#constructor` api docs below)
### Request Example
```javascript
const httpServer; // previously created with `http.createServer();` from node.js api.
// create a server first, and then attach
const eioServer = require('engine.io').Server();
eioServer.attach(httpServer);
// or call the module as a function to get `Server`
const eioServer = require('engine.io')();
eioServer.attach(httpServer);
// immediately attach
const eioServer = require('engine.io')(httpServer);
// with custom options
const eioServer = require('engine.io')(httpServer, {
maxHttpBufferSize: 1e3
});
```
```
--------------------------------
### Initialize Socket.IO Client and Listeners
Source: https://github.com/socketio/socket.io/blob/main/examples/nwjs-example/index.html
Sets up the Socket.IO client, registers listeners for status and transport updates, and sends an initial 'hello' event. Ensure the './index' module is correctly imported.
```javascript
const { registerListeners, emit } = require("./index");
const statusSpan = document.getElementById("status");
const transportSpan = document.getElementById("transport");
statusSpan.innerText = "Disconnected";
transportSpan.innerText = "N/A";
registerListeners({ statusSpan, transportSpan });
emit("hello", "world");
```
--------------------------------
### HTTP GET Request for Polling Transport
Source: https://github.com/socketio/socket.io/blob/main/docs/engine.io-protocol/v4-current.md
The client initiates a connection using an HTTP GET request with the 'polling' transport. This is the default method for establishing a connection.
```http
GET /engine.io/?EIO=4&transport=polling
```
--------------------------------
### HTTP GET Request for WebSocket Transport
Source: https://github.com/socketio/socket.io/blob/main/docs/engine.io-protocol/v4-current.md
For a WebSocket-only session, the client sends an HTTP GET request specifying the 'websocket' transport. This is followed by an HTTP 101 Switching Protocols response.
```http
GET /engine.io/?EIO=4&transport=websocket
```
--------------------------------
### Node.js Cluster and Redis Setup for Socket.IO
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-cluster-engine/README.md
Combine Node.js cluster and Redis for a robust Socket.IO setup. This configuration allows load balancing across processes and uses Redis for communication.
```javascript
import cluster from "node:cluster";
import process from "node:process";
import { availableParallelism } from "node:os";
import { createClient } from "redis";
import { setupPrimaryWithRedis, NodeClusterEngine } from "@socket.io/cluster-engine";
import { createServer } from "node:http";
import { Server } from "socket.io";
if (cluster.isPrimary) {
console.log(`Primary ${process.pid} is running`);
const numCPUs = availableParallelism();
// fork workers
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
const pubClient = createClient();
const subClient = pubClient.duplicate();
await Promise.all([
pubClient.connect(),
subClient.connect(),
]);
// setup connection between and within the clusters
setupPrimaryWithRedis(pubClient, subClient);
// needed for packets containing Buffer objects (you can ignore it if you only send plaintext objects)
cluster.setupPrimary({
serialization: "advanced",
});
cluster.on("exit", (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
const httpServer = createServer((req, res) => {
res.writeHead(404).end();
});
const engine = new NodeClusterEngine();
engine.attach(httpServer, {
path: "/socket.io/"
});
const io = new Server();
io.bind(engine);
// workers will share the same port
httpServer.listen(3000);
console.log(`Worker ${process.pid} started`);
}
```
--------------------------------
### Socket.IO with Module Syntax
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io/Readme.md
Demonstrates using Socket.IO with modern JavaScript module syntax. This requires a compatible server instance.
```js
import { Server } from "socket.io";
const io = new Server(server);
io.listen(3000);
```
--------------------------------
### HTTP Long-Polling: Receiving Data
Source: https://github.com/socketio/socket.io/blob/main/docs/engine.io-protocol/v4-current.md
Shows the client-server communication for receiving data via HTTP GET requests in the long-polling transport. Maintains packet order by limiting active GET requests.
```http
CLIENT SERVER
│ GET /engine.io/?EIO=4&transport=polling&sid=... │
│ ──────────────────────────────────────────────────► │
│ . │
│ . │
│ . │
│ . │
│ ◄─────────────────────────────────────────────────┘ │
│ HTTP 200 │
```
--------------------------------
### Connect to Socket.IO (v0.6.x)
Source: https://github.com/socketio/socket.io/wiki/Migrating-0.6-to-0.7+
In v0.6.x, instantiate a socket and connect to it using `io.Socket` and `socket.connect()`.
```javascript
var socket = new io.Socket(host, options);
socket.connect();
```
--------------------------------
### Initialize Emitter with Redis Client
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-redis-streams-emitter/README.md
Basic initialization of the Emitter class with a pre-configured Redis client.
```javascript
const io = new Emitter(redisClient);
```
--------------------------------
### Get Session ID (v0.7.x)
Source: https://github.com/socketio/socket.io/wiki/Migrating-0.6-to-0.7+
The `sessionId` property from v0.6.x is now simply `.id` in v0.7.x.
```javascript
// v0.6.x
var sid = socket.sessionId;
// v0.7.x
var sid = socket.id;
```
--------------------------------
### Generate Bundles
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-client/RELEASING.md
Execute this command to create the necessary bundles for distribution.
```bash
npm run build
```
--------------------------------
### Initialize Socket.IO Client
Source: https://github.com/socketio/socket.io/blob/main/examples/express-session-example/ts/index.html
Establishes a connection to the Socket.IO server. Can be configured to use only WebSockets if needed.
```javascript
const socket = io({
// with WebSocket only
// transports: ["websocket"],
});
```
--------------------------------
### Open Chrome Browser
Source: https://github.com/socketio/socket.io/blob/main/examples/webtransport/README.md
Use this script to open the Chrome browser, likely to access the WebTransport example.
```shell
# open a Chrome browser
$ ./open_chrome.sh
```
--------------------------------
### WebSocket Packet Format Example
Source: https://github.com/socketio/socket.io/blob/main/docs/engine.io-protocol/v4-current.md
Illustrates the simple format for Engine.IO packets sent over WebSocket, where each packet is in its own frame.
```text
4hello
```
--------------------------------
### Initialize Socket.IO Server
Source: https://github.com/socketio/socket.io/wiki/Configuring-Socket.IO
Use this to initialize a Socket.IO server, optionally specifying a port and configuration options. The `.set()` method can be used for further configuration.
```javascript
var socket = require('socket.io').listen(80, {
// options can go here
});
// or you can use the .set method
socket.set(key, value);
```
--------------------------------
### Server Listen Method
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io/README.md
Explains how to use the `listen` method to create an HTTP server that listens on a specific port and attaches Engine.IO to it. Regular HTTP requests will receive a '501 Not Implemented' response.
```APIDOC
## Server Listen Method
### Description
Creates an `http.Server` which listens on the given port and attaches WS to it. It returns `501 Not Implemented` for regular http requests.
### Parameters
- `Number`: port to listen on.
- `Object`: optional, options object
- `Function`: callback for `listen`.
### Options
- All options from `Server.attach` method, documented below.
- **Additionally** See Server `constructor` below for options you can pass for creating the new Server
### Returns
`Server`
### Request Example
```javascript
const engine = require('engine.io');
const server = engine.listen(3000, {
pingTimeout: 2000,
pingInterval: 10000
});
server.on('connection', /* ... */);
```
```
--------------------------------
### Listening for Manager Events in Socket.IO Client
Source: https://github.com/socketio/socket.io/wiki/Migrating-to-1.0
Example of how to subscribe to events emitted by the Socket.IO client manager, such as connection-related events.
```javascript
var manager = io.Manager('url', { /* options */ });
var socket = manager.socket('/namespace');
manager.on('event_name_like_reconnect_attempt', function() {
});
```
--------------------------------
### Encode and Decode Packet - Standalone
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io-parser/Readme.md
Demonstrates encoding a message packet with binary data and then decoding it. Ensure the 'engine.io-parser' package is installed.
```javascript
const parser = require("engine.io-parser");
const data = Buffer.from([ 1, 2, 3, 4 ]);
parser.encodePacket({ type: "message", data }, encoded => {
const decodedData = parser.decodePacket(encoded); // decodedData === data
});
```
--------------------------------
### Compile and Minify for Production
Source: https://github.com/socketio/socket.io/blob/main/examples/basic-crud-application/vue-client/README.md
Execute this command to compile and minify the project for production deployment. This optimizes the code for performance.
```bash
yarn build
```
--------------------------------
### Build App Bundle with Browserify
Source: https://github.com/socketio/socket.io/blob/main/packages/engine.io-parser/Readme.md
Command to bundle a JavaScript application using browserify.
```bash
browserify app.js > bundle.js
```
--------------------------------
### Redis Setup for Socket.IO
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-cluster-engine/README.md
Configure Socket.IO to use Redis for inter-process communication. Ensure Redis clients are connected before creating the engine.
```javascript
import { createServer } from "node:http";
import { createClient } from "redis";
import { RedisEngine } from "@socket.io/cluster-engine";
import { Server } from "socket.io";
const httpServer = createServer((req, res) => {
res.writeHead(404).end();
});
const pubClient = createClient();
const subClient = pubClient.duplicate();
await Promise.all([
pubClient.connect(),
subClient.connect(),
]);
const engine = new RedisEngine(pubClient, subClient);
engine.attach(httpServer, {
path: "/socket.io/"
});
const io = new Server();
io.bind(engine);
httpServer.listen(3000);
```
--------------------------------
### Send Message to Current Client
Source: https://github.com/socketio/socket.io/wiki/How-do-I-send-a-response-to-all-clients-except-sender?
Use `socket.emit()` to send a message only to the client that initiated the current request. No special setup is required.
```javascript
socket.emit('message', "this is a test");
```
--------------------------------
### Configure RedisStore for Socket.IO
Source: https://github.com/socketio/socket.io/wiki/Configuring-Socket.IO
Use RedisStore for client storage when scaling Socket.IO across multiple processes or servers. Requires Redis to be installed and running.
```javascript
var RedisStore = require('socket.io/lib/stores/redis')
, redis = require('socket.io/node_modules/redis')
, pub = redis.createClient()
, sub = redis.createClient()
, client = redis.createClient();
io.set('store', new RedisStore({
redisPub : pub
, redisSub : sub
, redisClient : client
}));
```
--------------------------------
### Build Nuxt Application for Production
Source: https://github.com/socketio/socket.io/blob/main/examples/nuxt-example/README.md
Build the Nuxt application for production deployment using different package managers.
```bash
# npm
npm run build
# pnpm
pnpm build
# yarn
yarn build
# bun
bun run build
```
--------------------------------
### Configure Socket.IO Server Initialization
Source: https://github.com/socketio/socket.io/wiki/Migrating-to-1.0
Use this method for configuring Socket.IO options during server initialization, as `io.set` is no longer supported. Some options are still supported for backward compatibility.
```javascript
var socket = require('socket.io')({
// options go here
});
```
--------------------------------
### Emitter Initialization
Source: https://github.com/socketio/socket.io/blob/main/packages/socket.io-postgres-emitter/README.md
Initializes the Emitter with a PostgreSQL connection pool.
```APIDOC
## Emitter(pool[, nsp][, opts])
### Description
Initializes the Emitter with a PostgreSQL connection pool.
### Parameters
#### Path Parameters
- **pool** (Pool) - Required - A Pool object from the `pg` package.
- **nsp** (string) - Optional - The namespace to use.
- **opts** (object) - Optional - Additional options.
### Request Example
```javascript
const { Emitter } = require("@socket.io/postgres-emitter");
const { Pool } = require("pg");
const pool = new Pool({
user: "postgres",
host: "localhost",
database: "postgres",
password: "changeit",
port: 5432,
});
const io = new Emitter(pool);
```
```