### Install Tape for Testing Source: https://socket.io/docs/v4/testing Install the Tape testing framework using npm. ```bash npm install --save-dev tape ``` -------------------------------- ### Install Google Cloud Pub/Sub Adapter Source: https://socket.io/docs/v4/gcp-pubsub-adapter Install the adapter using npm. This command fetches and installs the necessary package for your project. ```bash npm install @socket.io/gcp-pubsub-adapter ``` -------------------------------- ### Install @socket.io/cluster-adapter with Bun Source: https://socket.io/docs/v4/tutorial/step-9 Install the cluster adapter for Socket.IO using Bun. ```bash bun add @socket.io/cluster-adapter ``` -------------------------------- ### Install @socket.io/pm2 Source: https://socket.io/docs/v4/pm2 Install the @socket.io/pm2 package globally. If pm2 is already installed, it needs to be removed first. ```bash npm install -g @socket.io/pm2 ``` ```bash npm remove -g pm2 ``` -------------------------------- ### Install @socket.io/cluster-adapter with pnpm Source: https://socket.io/docs/v4/tutorial/step-9 Install the cluster adapter for Socket.IO using pnpm. ```bash pnpm add @socket.io/cluster-adapter ``` -------------------------------- ### Install Socket.IO with Bun Source: https://socket.io/docs/v4/server-installation Use this command to install the latest release of Socket.IO using Bun. ```bash bun add socket.io ``` -------------------------------- ### Install Postgres Adapter Source: https://socket.io/docs/v4/postgres-adapter Install the necessary packages for the Postgres adapter and PostgreSQL driver. ```bash npm install @socket.io/postgres-adapter pg ``` -------------------------------- ### Install SQLite with Bun Source: https://socket.io/docs/v4/tutorial/step-7 Installs the necessary packages for using SQLite with Socket.IO via Bun. ```bash bun add sqlite sqlite3 ``` -------------------------------- ### Install Express Source: https://socket.io/docs/v4/tutorial/step-1 Installs the specified version of the Express framework. This command should be run in the project directory. ```bash npm install express@4 ``` -------------------------------- ### Server Example with Volatile Events Source: https://socket.io/docs/v4/emitting-events Server logs connection and 'ping' events. This setup is often used with volatile events for high-frequency data where only the latest value matters. ```javascript io.on("connection", (socket) => { console.log("connect"); socket.on("ping", (count) => { console.log(count); }); }); ``` -------------------------------- ### Install Socket.IO Cluster Adapter Source: https://socket.io/docs/v4/cluster-adapter Install the cluster adapter package using npm. ```bash npm install @socket.io/cluster-adapter ``` -------------------------------- ### Install Socket.IO Redis Emitter and Redis Source: https://socket.io/docs/v4/redis-adapter Install the necessary packages using npm. This is the first step before using the Redis emitter. ```bash npm install @socket.io/redis-emitter redis ``` -------------------------------- ### Install Socket.IO with Yarn Source: https://socket.io/docs/v4/server-installation Use this command to install the latest release of Socket.IO using Yarn. ```bash yarn add socket.io ``` -------------------------------- ### Install @socket.io/cluster-adapter with Yarn Source: https://socket.io/docs/v4/tutorial/step-9 Install the cluster adapter for Socket.IO using Yarn. ```bash yarn add @socket.io/cluster-adapter ``` -------------------------------- ### Install MongoDB Adapter Source: https://socket.io/docs/v4/mongo-adapter Install the necessary packages for the MongoDB adapter and MongoDB driver. ```bash npm install @socket.io/mongo-adapter mongodb ``` -------------------------------- ### Install Bun Engine for Socket.IO Source: https://socket.io/docs/v4/server-installation Install the `@socket.io/bun-engine` package for a Bun-specific Socket.IO engine. ```bash bun add socket.io @socket.io/bun-engine ``` -------------------------------- ### Install Redis Adapter Source: https://socket.io/docs/v4/redis-adapter Install the Redis adapter package using npm. This is the first step to enable Redis-based scaling for Socket.IO. ```bash npm install @socket.io/redis-adapter ``` -------------------------------- ### Install Socket.IO with NPM Source: https://socket.io/docs/v4/server-installation Use this command to install the latest release of Socket.IO using npm. ```bash npm install socket.io ``` -------------------------------- ### Initialize Socket.IO with Hono (Node.js TypeScript) Source: https://socket.io/docs/v4/server-initialization This TypeScript example shows how to integrate Socket.IO with Hono, including type casting for the HTTP server. Ensure you have the necessary Node.js HTTP types installed. ```typescript import { Hono } from "hono"; import { serve } from "@hono/node-server"; import { Server } from "socket.io"; import type { Server as HTTPServer } from "node:http"; const app = new Hono(); const httpServer = serve({ fetch: app.fetch, port: 3000, }); const io = new Server(httpServer as HTTPServer, { /* options */ }); io.on("connection", (socket) => { // ... }); ``` -------------------------------- ### Install eiows WebSocket Server with Bun Source: https://socket.io/docs/v4/server-installation Install the eiows package, an alternative WebSocket server implementation, using Bun. ```bash bun add eiows ``` -------------------------------- ### Install Postgres Emitter Source: https://socket.io/docs/v4/postgres-adapter Install the necessary packages for the Postgres emitter and PostgreSQL driver. ```bash npm install @socket.io/postgres-emitter pg ``` -------------------------------- ### Install Socket.IO Admin UI Package Source: https://socket.io/docs/v4/admin-ui Install the admin UI package using npm. ```bash npm i @socket.io/admin-ui ``` -------------------------------- ### Install Socket.IO Client via Bun Source: https://socket.io/docs/v4/client-installation Install the Socket.IO client package using Bun. Bun is a new JavaScript runtime, bundler, transpiler, and package manager. ```bash bun add socket.io-client ``` -------------------------------- ### Install Vitest Source: https://socket.io/docs/v4/testing Install Vitest as a development dependency for your project. ```bash npm install --save-dev vitest ``` -------------------------------- ### Install Optional Performance Packages with Bun Source: https://socket.io/docs/v4/server-installation Install optional bufferutil and utf-8-validate packages using Bun for improved performance. These are binary add-ons. ```bash bun add --optional bufferutil utf-8-validate ``` -------------------------------- ### Install Socket.IO with pnpm Source: https://socket.io/docs/v4/server-installation Use this command to install the latest release of Socket.IO using pnpm. ```bash pnpm add socket.io ``` -------------------------------- ### Install Redis Streams Adapter Source: https://socket.io/docs/v4/redis-streams-adapter Install the necessary packages for the Socket.IO Redis Streams adapter. ```bash npm install @socket.io/redis-streams-adapter redis ``` -------------------------------- ### Install SQLite with PNPM Source: https://socket.io/docs/v4/tutorial/step-7 Installs the necessary packages for using SQLite with Socket.IO via PNPM. ```bash pnpm add sqlite sqlite3 ``` -------------------------------- ### Install Optional Performance Packages with NPM Source: https://socket.io/docs/v4/server-installation Install optional bufferutil and utf-8-validate packages using npm for improved performance. These are binary add-ons. ```bash npm install --save-optional bufferutil utf-8-validate ``` -------------------------------- ### Install µWebSockets.js for Socket.IO with Bun Source: https://socket.io/docs/v4/server-installation Install the µWebSockets.js package with a specific version for use with Socket.IO via Bun. ```bash bun add uWebSockets.js@uNetworking/uWebSockets.js#v20.52.0 ``` -------------------------------- ### Install eiows WebSocket Server with NPM Source: https://socket.io/docs/v4/server-installation Install the eiows package, an alternative WebSocket server implementation, using npm. ```bash npm install eiows ``` -------------------------------- ### Install SQLite with NPM Source: https://socket.io/docs/v4/tutorial/step-7 Installs the necessary packages for using SQLite with Socket.IO via NPM. ```bash npm install sqlite sqlite3 ``` -------------------------------- ### Install SQLite with Yarn Source: https://socket.io/docs/v4/tutorial/step-7 Installs the necessary packages for using SQLite with Socket.IO via Yarn. ```bash yarn add sqlite sqlite3 ``` -------------------------------- ### Install Optional Performance Packages with pnpm Source: https://socket.io/docs/v4/server-installation Install optional bufferutil and utf-8-validate packages using pnpm for improved performance. These are binary add-ons. ```bash pnpm add -O bufferutil utf-8-validate ``` -------------------------------- ### Install Vitest Source: https://socket.io/docs/v4/testing Installs Vitest as a development dependency using npm. This is the first step to setting up the testing environment. ```bash npm install --save-dev vitest ``` -------------------------------- ### Install Mocha, Chai, and Types for Testing (TypeScript) Source: https://socket.io/docs/v4/testing Install Mocha, Chai, and their corresponding TypeScript type definitions for developing and testing TypeScript applications. ```bash npm install --save-dev mocha chai @types/mocha @types/chai ``` -------------------------------- ### Install Socket.IO Client via NPM Source: https://socket.io/docs/v4/client-installation Install the Socket.IO client package using NPM. This is the recommended method for projects using module bundlers. ```bash npm install socket.io-client ``` -------------------------------- ### Install eiows WebSocket Server with pnpm Source: https://socket.io/docs/v4/server-installation Install the eiows package, an alternative WebSocket server implementation, using pnpm. ```bash pnpm add eiows ``` -------------------------------- ### Install eiows WebSocket Server with Yarn Source: https://socket.io/docs/v4/server-installation Install the eiows package, an alternative WebSocket server implementation, using Yarn. ```bash yarn add eiows ``` -------------------------------- ### Install µWebSockets.js for Socket.IO with NPM Source: https://socket.io/docs/v4/server-installation Install the µWebSockets.js package with a specific version for use with Socket.IO via npm. ```bash npm install uWebSockets.js@uNetworking/uWebSockets.js#v20.52.0 ``` -------------------------------- ### Install Optional Performance Packages with Yarn Source: https://socket.io/docs/v4/server-installation Install optional bufferutil and utf-8-validate packages using Yarn for improved performance. These are binary add-ons. ```bash yarn add --optional bufferutil utf-8-validate ``` -------------------------------- ### Install AWS SQS Adapter Source: https://socket.io/docs/v4/aws-sqs-adapter Install the AWS SQS adapter package using npm. This is the first step to integrate SQS for inter-node communication. ```bash npm install @socket.io/aws-sqs-adapter ``` -------------------------------- ### Install µWebSockets.js for Socket.IO with pnpm Source: https://socket.io/docs/v4/server-installation Install the µWebSockets.js package with a specific version for use with Socket.IO via pnpm. ```bash pnpm add uWebSockets.js@uNetworking/uWebSockets.js#v20.52.0 ``` -------------------------------- ### Client-side Custom Path with Namespace Source: https://socket.io/docs/v4/client-options Example of configuring a custom path and specifying a namespace in the client connection URI. ```javascript import { io } from "socket.io-client"; const socket = io("https://example.com/order", { path: "/my-custom-path/" }); ``` -------------------------------- ### Install Webpack and Socket.IO Dependencies Source: https://socket.io/docs/v4/server-with-bundlers Install necessary development dependencies for Webpack bundling, including Socket.IO and its optional dependencies. ```bash npm install -D webpack webpack-cli socket.io bufferutil utf-8-validate ``` -------------------------------- ### Server-side MessagePack Parser Setup Source: https://socket.io/docs/v4/custom-parser Configure the Socket.IO server to use the MessagePack parser for efficient binary packet handling. Ensure the 'socket.io-msgpack-parser' package is installed. ```javascript import { Server } from "socket.io"; import customParser from "socket.io-msgpack-parser"; const io = new Server({ parser: customParser }); ``` -------------------------------- ### Integrate Socket.IO with µWebSockets.js Source: https://socket.io/docs/v4/server-installation Example demonstrating how to attach a Socket.IO server to a µWebSockets.js application. ```javascript const { App } = require("uWebSockets.js"); const { Server } = require("socket.io"); const app = App(); const io = new Server(); io.attachApp(app); io.on("connection", (socket) => { // ... }); app.listen(3000, (token) => { if (!token) { console.warn("port already in use"); } }); ``` -------------------------------- ### Setup HTTP Server and Socket.IO (ES Modules) Source: https://socket.io/docs/v4/testing Sets up an HTTP server and Socket.IO instance using ES module syntax, then connects a client. This is a prerequisite for most Socket.IO tests. ```javascript import { test } from "tape"; import { createServer } from "node:http"; import { io as ioc } from "socket.io-client"; import { Server } from "socket.io"; let io, serverSocket, clientSocket; function waitFor(socket, event) { return new Promise((resolve) => { socket.once(event, resolve); }); } test("setup", (t) => { const httpServer = createServer(); io = new Server(httpServer); httpServer.listen(() => { const port = httpServer.address().port; clientSocket = ioc(`http://localhost:${port}`); io.on("connection", (socket) => { serverSocket = socket; }); clientSocket.on("connect", t.end); }); }); ``` -------------------------------- ### Install ws Native Add-ons Source: https://socket.io/docs/v4/performance-tuning Install optional native add-ons for bufferutil and utf-8-validate to improve WebSocket frame operations and UTF-8 validation. These packages are optional and the WebSocket server will fallback to a JavaScript implementation if they are not available. ```bash $ npm install --save-optional bufferutil utf-8-validate ``` -------------------------------- ### Setup HTTP Server and Socket.IO (CommonJS) Source: https://socket.io/docs/v4/testing Sets up an HTTP server and Socket.IO instance, then connects a client. This is a prerequisite for most Socket.IO tests. ```javascript const test = require("tape"); const { createServer } = require("node:http"); const { Server } = require("socket.io"); const ioc = require("socket.io-client"); let io, serverSocket, clientSocket; function waitFor(socket, event) { return new Promise((resolve) => { socket.once(event, resolve); }); } test("setup", (t) => { const httpServer = createServer(); io = new Server(httpServer); httpServer.listen(() => { const port = httpServer.address().port; clientSocket = ioc(`http://localhost:${port}`); io.on("connection", (socket) => { serverSocket = socket; }); clientSocket.on("connect", t.end); }); }); ``` -------------------------------- ### Migrate to @socket.io/redis-adapter Source: https://socket.io/docs/v4/redis-adapter This example shows the 'After' migration steps from the `socket.io-redis` package to the new `@socket.io/redis-adapter`. It requires creating Redis clients explicitly using `createClient` from the `redis` package. ```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)); ``` -------------------------------- ### Install Socket.IO Client via PNPM Source: https://socket.io/docs/v4/client-installation Install the Socket.IO client package using PNPM. PNPM is a fast, disk-space-efficient package manager. ```bash pnpm add socket.io-client ``` -------------------------------- ### Install Socket.IO Client for Webpack 5 (Node.js) Source: https://socket.io/docs/v4/client-with-bundlers Install necessary development dependencies for bundling the Socket.IO client with Webpack 5 for Node.js environments. ```bash npm i -D socket.io-client webpack webpack-cli ``` -------------------------------- ### Socket.IO Client Dependency Tree Source: https://socket.io/docs/v4/client-installation Illustrates the dependency tree for a basic installation of the Socket.IO client, showing core packages and their versions. ```plaintext └─┬ socket.io-client@4.8.1 ├── @socket.io/component-emitter@3.1.2 ├─┬ debug@4.3.7 │ └── ms@2.1.3 ├─┬ engine.io-client@6.6.3 │ ├── @socket.io/component-emitter@3.1.2 deduped │ ├── debug@4.3.7 deduped │ ├── engine.io-parser@5.2.3 │ ├─┬ ws@8.17.1 │ │ ├── UNMET OPTIONAL DEPENDENCY bufferutil@^4.0.1 │ │ └── UNMET OPTIONAL DEPENDENCY utf-8-validate@>=5.0.2 │ └── xmlhttprequest-ssl@2.1.2 └─┬ socket.io-parser@4.2.4 ├── @socket.io/component-emitter@3.1.2 deduped └── debug@4.3.7 deduped ``` -------------------------------- ### Setup Socket.IO Server and Client for Testing Source: https://socket.io/docs/v4/testing This snippet sets up an HTTP server, a Socket.IO server instance, and a Socket.IO client instance for testing purposes. It ensures the server and client are connected before proceeding with tests. ```javascript const { beforeAll, afterAll, describe, it, expect } = require("vitest"); const { createServer } = require("node:http"); const { Server } = require("socket.io"); const ioc = require("socket.io-client"); function waitFor(socket, event) { return new Promise((resolve) => { socket.once(event, resolve); }); } describe("my awesome project", () => { let io, serverSocket, clientSocket; beforeAll(() => { return new Promise((resolve) => { const httpServer = createServer(); io = new Server(httpServer); httpServer.listen(() => { const port = httpServer.address().port; clientSocket = ioc(`http://localhost:${port}`); io.on("connection", (socket) => { serverSocket = socket; }); clientSocket.on("connect", resolve); }); }); }); afterAll(() => { io.close(); clientSocket.disconnect(); }); it("should work", () => { return new Promise((resolve) => { clientSocket.on("hello", (arg) => { expect(arg).toEqual("world"); resolve(); }); serverSocket.emit("hello", "world"); }); }); it("should work with an acknowledgement", () => { return new Promise((resolve) => { serverSocket.on("hi", (cb) => { cb("hola"); }); clientSocket.emit("hi", (arg) => { expect(arg).toEqual("hola"); resolve(); }); }); }); it("should work with emitWithAck()", async () => { serverSocket.on("foo", (cb) => { cb("bar"); }); const result = await clientSocket.emitWithAck("foo"); expect(result).toEqual("bar"); }); it("should work with waitFor()", () => { clientSocket.emit("baz"); return waitFor(serverSocket, "baz"); }); }); ``` ```javascript import { beforeAll, afterAll, describe, it, expect } from "vitest"; import { createServer } from "node:http"; import { io as ioc } from "socket.io-client"; import { Server } from "socket.io"; function waitFor(socket, event) { return new Promise((resolve) => { socket.once(event, resolve); }); } describe("my awesome project", () => { let io, serverSocket, clientSocket; beforeAll(() => { return new Promise((resolve) => { const httpServer = createServer(); io = new Server(httpServer); httpServer.listen(() => { const port = httpServer.address().port; clientSocket = ioc(`http://localhost:${port}`); io.on("connection", (socket) => { serverSocket = socket; }); clientSocket.on("connect", resolve); }); }); }); afterAll(() => { io.close(); clientSocket.disconnect(); }); it("should work", () => { return new Promise((resolve) => { clientSocket.on("hello", (arg) => { expect(arg).toEqual("world"); resolve(); }); serverSocket.emit("hello", "world"); }); }); it("should work with an acknowledgement", () => { return new Promise((resolve) => { serverSocket.on("hi", (cb) => { cb("hola"); }); clientSocket.emit("hi", (arg) => { expect(arg).toEqual("hola"); resolve(); }); }); }); it("should work with emitWithAck()", async () => { serverSocket.on("foo", (cb) => { cb("bar"); }); const result = await clientSocket.emitWithAck("foo"); expect(result).toEqual("bar"); }); it("should work with waitFor()", () => { clientSocket.emit("baz"); return waitFor(serverSocket, "baz"); }); }); ``` -------------------------------- ### Install Socket.IO Client for Rollup.js (Node.js) Source: https://socket.io/docs/v4/client-with-bundlers Install necessary development dependencies for bundling the Socket.IO client with Rollup.js for Node.js environments. Includes plugins for Node.js module resolution, CommonJS support, and minification. ```bash npm i -D socket.io-client rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs rollup-plugin-uglify ``` -------------------------------- ### Setup HTTP Server and Socket.IO (TypeScript) Source: https://socket.io/docs/v4/testing Sets up an HTTP server and Socket.IO instance with TypeScript types, then connects a client. This is a prerequisite for most Socket.IO tests. ```typescript import { test } from "tape"; import { createServer } from "node:http"; import { type AddressInfo } from "node:net"; import { io as ioc, type Socket as ClientSocket } from "socket.io-client"; import { Server, type Socket as ServerSocket } from "socket.io"; let io: Server, serverSocket: ServerSocket, clientSocket: ClientSocket; function waitFor(socket: ServerSocket | ClientSocket, event: string) { return new Promise((resolve) => { socket.once(event, resolve); }); } test("setup", (t) => { ``` -------------------------------- ### Configure Socket.IO with Bun Engine Source: https://socket.io/docs/v4/server-installation Example of binding a Socket.IO server to the Bun-specific engine for enhanced performance and scalability with Bun. ```javascript import { Server as Engine } from "@socket.io/bun-engine"; import { Server } from "socket.io"; const io = new Server(); const engine = new Engine({ path: "/socket.io/", }); io.bind(engine); io.on("connection", (socket) => { // ... }); export default { port: 3000, idleTimeout: 30, // must be greater than the "pingInterval" option of the engine, which defaults to 25 seconds ...engine.handler(), }; ``` -------------------------------- ### Install Socket.IO Client for Webpack 5 (Browser) Source: https://socket.io/docs/v4/client-with-bundlers Install necessary development dependencies for bundling the Socket.IO client with Webpack 5 for browser environments. Includes Babel for transpilation and a plugin to remove debug statements. ```bash npm i -D socket.io-client webpack webpack-cli babel-loader @babel/core @babel/preset-env \ @babel/plugin-transform-object-assign webpack-remove-debug ``` -------------------------------- ### Initialize Socket.IO with Pub/Sub Adapter Source: https://socket.io/docs/v4/gcp-pubsub-adapter Set up a Socket.IO server using the Google Cloud Pub/Sub adapter. Ensure you have authenticated with Google Cloud and replaced 'your-project-id' and 'topicNameOrId' with your actual values. The adapter requires initialization before the server starts listening. ```javascript import { PubSub } from "@google-cloud/pubsub"; import { Server } from "socket.io"; import { createAdapter } from "@socket.io/gcp-pubsub-adapter"; const pubsub = new PubSub({ projectId: "your-project-id" }); const topic = pubsub.topic(topicNameOrId); const io = new Server({ adapter: createAdapter(topic) }); // wait for the creation of the pub/sub subscription await io.of("/").adapter.init(); io.listen(3000); ``` -------------------------------- ### Node.js Socket.IO Server Configuration and Event Handling Source: https://socket.io/docs/v4/socket-io-protocol Provides an example of setting up a Socket.IO server in Node.js with custom configurations for ping intervals, timeouts, max payload size, and CORS. It also demonstrates handling 'connection' events, emitting authentication data, and managing 'message' and 'message-with-ack' events. ```javascript import { Server } from "socket.io"; const io = new Server(3000, { pingInterval: 300, pingTimeout: 200, maxPayload: 1000000, cors: { origin: "*" } }); io.on("connection", (socket) => { socket.emit("auth", socket.handshake.auth); socket.on("message", (...args) => { socket.emit.apply(socket, ["message-back", ...args]); }); socket.on("message-with-ack", (...args) => { const ack = args.pop(); ack(...args); }) }); io.of("/custom").on("connection", (socket) => { socket.emit("auth", socket.handshake.auth); }); ``` -------------------------------- ### Initialize Server with Port Source: https://socket.io/docs/v4/server-api Create a Socket.IO server instance that listens on a specified port. This is a convenient way to start a server without an explicit HTTP server object. ```javascript import { Server } from "socket.io"; const io = new Server(3000, { // options }); io.on("connection", (socket) => { // ... }); ``` -------------------------------- ### Initialize Socket.IO Server with Postgres Adapter Source: https://socket.io/docs/v4/postgres-adapter Set up a Socket.IO server and attach the Postgres adapter using a pg.Pool instance. Ensure the 'socket_io_attachments' table is created if it doesn't exist. ```typescript import { Server } from "socket.io"; import { createAdapter } from "@socket.io/postgres-adapter"; import pg from "pg"; const io = new Server(); const pool = new pg.Pool({ user: "postgres", host: "localhost", database: "postgres", password: "changeit", port: 5432, }); pool.query(` CREATE TABLE IF NOT EXISTS socket_io_attachments ( id bigserial UNIQUE, created_at timestamptz DEFAULT NOW(), payload bytea ); `); pool.on("error", (err) => { console.error("Postgres error", err); }); io.adapter(createAdapter(pool)); io.listen(3000); ``` -------------------------------- ### Clone Chat Example Source: https://socket.io/docs/v4/tutorial/ending-notes Clone the Socket.IO chat example repository from GitHub to your local machine. ```bash git clone https://github.com/socketio/chat-example.git ``` -------------------------------- ### Initialize Server with Options Only Source: https://socket.io/docs/v4/server-api Create a Socket.IO server instance using only options, and then explicitly tell it to listen on a port. Useful when you want to configure the server before binding it to a port. ```javascript import { Server } from "socket.io"; const io = new Server({ // options }); io.on("connection", (socket) => { // ... }); io.listen(3000); ``` -------------------------------- ### Install Socket.IO Package Source: https://socket.io/docs/v4/tutorial/step-3 Install the socket.io package using npm. This command adds the dependency to your package.json file. ```bash npm install socket.io ``` -------------------------------- ### Client initialization for namespaces (same-origin) Source: https://socket.io/docs/v4/namespaces Initialize client-side connections to different namespaces. `io()` connects to the main namespace, while `io('/namespace-name')` connects to a specific custom namespace. ```javascript const socket = io(); // or io("/" ), the main namespace const orderSocket = io("/orders"); // the "orders" namespace const userSocket = io("/users"); // the "users" namespace ``` -------------------------------- ### Install µWebSockets.js for Socket.IO with Yarn Source: https://socket.io/docs/v4/server-installation Install the µWebSockets.js package with a specific version for use with Socket.IO via Yarn. ```bash yarn add uWebSockets.js@uNetworking/uWebSockets.js#v20.52.0 ``` -------------------------------- ### Install Jest for Development Source: https://socket.io/docs/v4/testing Installs Jest, a JavaScript testing framework, as a development dependency. This is required to run the test suite. ```bash npm install --save-dev jest ``` ```bash npm install --save-dev jest @types/jest ``` -------------------------------- ### Client Connection with io() Source: https://socket.io/docs/v4/client-api Demonstrates how to establish a Socket.IO connection using the `io()` method in different environments (standalone script, ESM, Node.js). ```APIDOC ## Client Connection with io() ### Description This section shows how to initialize a Socket.IO client connection using the global `io()` function or by importing it from the `socket.io-client` package. ### Usage Examples **Standalone Build:** ```html ``` **ESM Bundle:** ```html ``` **With Import Map:** ```html ``` **Node.js / CommonJS / ES Modules:** ```javascript // ES modules import { io } from "socket.io-client"; // CommonJS const { io } = require("socket.io-client"); const socket = io(); ``` -------------------------------- ### Initialize Socket.IO with Redis Adapter (redis package) Source: https://socket.io/docs/v4/redis-streams-adapter Set up Socket.IO with the Redis Streams adapter using the 'redis' package. Ensure the Redis client is connected before creating the adapter. ```javascript import { createClient } from "redis"; import { Server } from "socket.io"; import { createAdapter } from "@socket.io/redis-streams-adapter"; const redisClient = createClient({ url: "redis://localhost:6379" }); await redisClient.connect(); const io = new Server({ adapter: createAdapter(redisClient) }); io.listen(3000); ``` -------------------------------- ### Event Argument Validation Example Source: https://socket.io/docs/v4/listening-to-events Example demonstrating how to validate event arguments using external libraries like Joi. ```APIDOC ## Event Argument Validation ### Description The validation of event arguments is out of the scope of the Socket.IO library. This section provides an example using the 'joi' library for validation, particularly with acknowledgements. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters None ### Request Example ```javascript const Joi = require("joi"); const userSchema = Joi.object({ username: Joi.string().max(30).required(), email: Joi.string().email().required() }); io.on("connection", (socket) => { socket.on("create user", (payload, callback) => { if (typeof callback !== "function") { // not an acknowledgement return socket.disconnect(); } const { error, value } = userSchema.validate(payload); if (error) { return callback({ status: "Bad Request", error }); } // do something with the value, and then callback({ status: "OK" }); }); }); ``` ### Response None ``` -------------------------------- ### Install Mocha and Chai for Testing Source: https://socket.io/docs/v4/testing Install Mocha and Chai as development dependencies for your testing environment. These are common choices for JavaScript testing. ```bash npm install --save-dev mocha chai ``` -------------------------------- ### Socket.IO wsEngine Option Configuration (After) Source: https://socket.io/docs/v4/migrating-from-3-x-to-4-0 Demonstrates the updated format for the wsEngine option in Socket.IO 4.0, requiring the actual server class to be imported, resolving webpack bundling errors. ```javascript const io = require("socket.io")(httpServer, { wsEngine: require("eiows").Server }); ``` -------------------------------- ### Install MongoDB Emitter Source: https://socket.io/docs/v4/mongo-adapter Install the necessary packages for the MongoDB emitter and MongoDB driver to send packets from separate Node.js processes. ```bash npm install @socket.io/mongo-emitter mongodb ``` -------------------------------- ### Use eiows WebSocket Server Source: https://socket.io/docs/v4/performance-tuning Install and use the 'eiows' package as an alternative WebSocket server implementation. This requires setting the 'wsEngine' option when creating the Socket.IO server. ```bash $ npm install eiows ``` ```javascript const { createServer } = require("http"); const { Server } = require("socket.io"); const httpServer = createServer(); const io = new Server(httpServer, { wsEngine: require("eiows").Server }); ``` -------------------------------- ### Initialize package.json (CommonJS) Source: https://socket.io/docs/v4/tutorial/step-1 Defines the project's metadata and dependencies. Ensure the 'name' property is unique. ```json { "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "type": "commonjs", "dependencies": {} } ``` -------------------------------- ### Install Specific Socket.IO Version with Bun Source: https://socket.io/docs/v4/server-installation Install a specific version of Socket.IO using Bun by replacing 'version' with the desired version number. ```bash bun add socket.io@version ``` -------------------------------- ### Initialize Socket.IO with µWebSockets.js Source: https://socket.io/docs/v4/server-initialization Set up Socket.IO with µWebSockets.js. This approach uses `io.attachApp()` to integrate Socket.IO with the µWebSockets.js application. ```javascript import { App } from "uWebSockets.js"; import { Server } from "socket.io"; const app = App(); const io = new Server(); io.attachApp(app); io.on("connection", (socket) => { // ... }); app.listen(3000, (token) => { if (!token) { console.warn("port already in use"); } }); ``` -------------------------------- ### Install Specific Socket.IO Version with pnpm Source: https://socket.io/docs/v4/server-installation Install a specific version of Socket.IO using pnpm by replacing 'version' with the desired version number. ```bash pnpm add socket.io@version ``` -------------------------------- ### Install Specific Socket.IO Version with Yarn Source: https://socket.io/docs/v4/server-installation Install a specific version of Socket.IO using Yarn by replacing 'version' with the desired version number. ```bash yarn add socket.io@version ``` -------------------------------- ### Client Example with Volatile Events Source: https://socket.io/docs/v4/emitting-events Client emits 'ping' events every second using `volatile.emit`. This demonstrates sending frequent updates where dropped packets are acceptable. ```javascript let count = 0; setInterval(() => { socket.volatile.emit("ping", ++count); }, 1000); ``` -------------------------------- ### Initialize Socket.IO with HTTP/2 Server (CommonJS) Source: https://socket.io/docs/v4/server-initialization Set up a Socket.IO server using an HTTP/2 secure server with CommonJS modules. This example enables HTTP/1.1 fallback. ```javascript const { readFileSync } = require("fs"); const { createSecureServer } = require("http2"); const { Server } = require("socket.io"); const httpServer = createSecureServer({ allowHTTP1: true, key: readFileSync("/path/to/my/key.pem"), cert: readFileSync("/path/to/my/cert.pem") }); const io = new Server(httpServer, { /* options */ }); io.on("connection", (socket) => { // ... }); httpServer.listen(3000); ``` -------------------------------- ### Install Specific Socket.IO Version with NPM Source: https://socket.io/docs/v4/server-installation Install a specific version of Socket.IO using npm by replacing 'version' with the desired version number. ```bash npm install socket.io@version ``` -------------------------------- ### Install Artillery and Socket.IO v3/v4 Engine Source: https://socket.io/docs/v4/load-testing Install the necessary npm packages for Artillery and the custom engine required for Socket.IO v3/v4 compatibility. ```bash $ npm install artillery artillery-engine-socketio-v3 ``` -------------------------------- ### Install Socket.IO Client via Yarn Source: https://socket.io/docs/v4/client-installation Install the Socket.IO client package using Yarn. This is an alternative package manager for Node.js projects. ```bash yarn add socket.io-client ``` -------------------------------- ### Initialize Socket.IO with Fastify (ES Modules) Source: https://socket.io/docs/v4/server-initialization Set up Socket.IO with a Fastify server using ES module syntax. This requires Node.js to support ES modules. ```javascript import Fastify from "fastify"; import { Server } from "socket.io"; const fastify = Fastify(); const io = new Server(fastify.server, { /* options */ }); io.on("connection", (socket) => { // ... }); fastify.addHook("preClose", (done) => { // close all active connections on this server io.local.disconnectSockets(true); done(); }); fastify.listen({ port: 3000 }); ``` -------------------------------- ### Example Handshake Object Structure Source: https://socket.io/docs/v4/server-api An example of the structure of the handshake object, detailing fields like headers, time, address, query, and authentication payload. ```json const handshake = { headers: { "user-agent": "node-XMLHttpRequest", accept: "*/*", host: "localhost:3000", connection: "close" }, time: "Wed Jan 01 2020 01:00:00 GMT+0100 (Central European Standard Time)", address: "::ffff:127.0.0.1", xdomain: false, secure: false, issued: 1577836800000, url: "/socket.io/?EIO=4&transport=polling&t=OPAfXv5&b64=1", query: { EIO: "4", transport: "polling", t: "OPAfXv5", b64: "1" }, auth: {} } ``` -------------------------------- ### Get current transport name on server-side Source: https://socket.io/docs/v4/troubleshooting-connection-issues You can get the name of the current transport (e.g., 'polling' or 'websocket') on the server-side. This is useful for debugging connection issues. ```javascript io.on("connection", (socket) => { const transport = socket.conn.transport.name; // in most cases, "polling" socket.conn.on("upgrade", () => { const upgradedTransport = socket.conn.transport.name; // in most cases, "websocket" }); }); ``` -------------------------------- ### Basic Client Listen Source: https://socket.io/docs/v4/emitting-events Client listens for a 'hello' event and logs the received argument. This pairs with the server's basic emit. ```javascript socket.on("hello", (arg) => { console.log(arg); // world }); ``` -------------------------------- ### Get current transport name on client-side Source: https://socket.io/docs/v4/troubleshooting-connection-issues You can get the name of the current transport (e.g., 'polling' or 'websocket') on the client-side. This is useful for debugging connection issues. ```javascript socket.on("connect", () => { const transport = socket.io.engine.transport.name; // in most cases, "polling" socket.io.engine.on("upgrade", () => { const upgradedTransport = socket.io.engine.transport.name; // in most cases, "websocket" }); }); ``` -------------------------------- ### TypeScript Error Example Source: https://socket.io/docs/v4/client-installation An example of a TypeScript error that may occur if outdated types are used. Ensure you are using the types included within the 'socket.io-client' package. ```typescript Object literal may only specify known properties, and 'extraHeaders' does not exist in type 'ConnectOpts' ``` -------------------------------- ### Initialize package.json (ES Modules) Source: https://socket.io/docs/v4/tutorial/step-1 Defines the project's metadata and dependencies for ES module projects. Ensure the 'name' property is unique. ```json { "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "type": "module", "dependencies": {} } ``` -------------------------------- ### Get all connected sockets (Callback-based, v3) Source: https://socket.io/docs/v4/migrating-from-2-x-to-3-0 Before v4, `clients()` was used to get socket IDs, accepting a callback function. This method is now deprecated in favor of `allSockets()`. ```javascript // all sockets in default namespace io.clients((error, clients) => { console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB] }); // all sockets in the "chat" namespace io.of("/chat").clients((error, clients) => { console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD] }); // all sockets in the "chat" namespace and in the "general" room io.of("/chat").in("general").clients((error, clients) => { console.log(clients); // => [Anw2LatarvGVVXEIAAAD] }); ``` -------------------------------- ### Initialize Socket.IO with Koa (ES Modules) Source: https://socket.io/docs/v4/server-initialization Set up Socket.IO with a Koa server using ES module syntax. This requires Node.js to support ES modules. ```javascript import Koa from "koa"; import { createServer } from "http"; import { Server } from "socket.io"; const app = new Koa(); const httpServer = createServer(app.callback()); const io = new Server(httpServer, { /* options */ }); io.on("connection", (socket) => { // ... }); httpServer.listen(3000); ```