socket.io
- Version 4.8.1
- Published
- 1.41 MB
- 7 dependencies
- MIT license
Install
npm i socket.io
yarn add socket.io
pnpm add socket.io
Overview
node.js realtime framework server
Index
Classes
Socket
- broadcast
- client
- compress()
- conn
- connected
- data
- disconnect()
- disconnected
- emit()
- emitWithAck()
- except()
- handshake
- id
- in()
- join()
- leave()
- listenersAny()
- listenersAnyOutgoing()
- local
- nsp
- offAny()
- offAnyOutgoing()
- onAny()
- onAnyOutgoing()
- prependAny()
- prependAnyOutgoing()
- recovered
- request
- rooms
- send()
- timeout()
- to()
- use()
- volatile
- write()
Interfaces
Type Aliases
Classes
class BroadcastOperator
class BroadcastOperator<EmitEvents extends EventsMap, SocketData> implements TypedEventBroadcaster<EmitEvents> {}
constructor
constructor( adapter: Adapter, rooms?: Set<Room>, exceptRooms?: Set<Room>, flags?: any);
property local
readonly local: BroadcastOperator<EmitEvents, SocketData>;
Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
Example 1
// the “foo” event will be broadcast to all connected clients on this node io.local.emit("foo", "bar");
a new BroadcastOperator instance for chaining
property volatile
readonly volatile: BroadcastOperator<EmitEvents, SocketData>;
Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).
Example 1
io.volatile.emit("hello"); // the clients may or may not receive it
a new BroadcastOperator instance
method allSockets
allSockets: () => Promise<Set<SocketId>>;
Gets a list of clients.
Deprecated
this method will be removed in the next major release, please use Server#serverSideEmit or fetchSockets instead.
method compress
compress: (compress: boolean) => BroadcastOperator<EmitEvents, SocketData>;
Sets the compress flag.
Parameter compress
if
true
, compresses the sending data a new BroadcastOperator instanceExample 1
io.compress(false).emit("hello");
method disconnectSockets
disconnectSockets: (close?: boolean) => void;
Makes the matching socket instances disconnect.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Parameter close
whether to close the underlying connection
Example 1
// make all socket instances disconnect (the connections might be kept alive for other namespaces) io.disconnectSockets();
// make all socket instances in the "room1" room disconnect and close the underlying connections io.in("room1").disconnectSockets(true);
method emit
emit: <Ev extends EventNames<EmitEvents>>( ev: Ev, ...args: EventParams<EmitEvents, Ev>) => boolean;
Emits to all clients.
Example 1
// the “foo” event will be broadcast to all connected clients io.emit("foo", "bar");
// the “foo” event will be broadcast to all connected clients in the “room-101” room io.to("room-101").emit("foo", "bar");
// with an acknowledgement expected from all connected clients io.timeout(1000).emit("some-event", (err, responses) => { if (err) { // some clients did not acknowledge the event in the given delay } else { console.log(responses); // one response per client } });
Always true
method emitWithAck
emitWithAck: < Ev extends IfAny< | EmitEvents[IfAny< | EmitEvents[EventNames<EmitEvents>] | Last<Parameters<EmitEvents[EventNames<EmitEvents>]>>, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) >] | Last< Parameters< EmitEvents[IfAny< | EmitEvents[EventNames<EmitEvents>] | Last<Parameters<EmitEvents[EventNames<EmitEvents>]>>, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & string] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) >] > >, IfAny< | EmitEvents[EventNames<EmitEvents>] | Last<Parameters<EmitEvents[EventNames<EmitEvents>]>>, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) >, IfAny< | EmitEvents[EventNames<EmitEvents>] | Last<Parameters<EmitEvents[EventNames<EmitEvents>]>>, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) > extends ( LooseParameters< Last< Parameters< EmitEvents[IfAny< | EmitEvents[EventNames<EmitEvents>] | Last< Parameters<EmitEvents[EventNames<EmitEvents>]> >, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last< Parameters< EmitEvents[keyof EmitEvents & string] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & string] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) >] > > >[0] extends Error ? IfAny< | EmitEvents[EventNames<EmitEvents>] | Last<Parameters<EmitEvents[EventNames<EmitEvents>]>>, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & string] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) > : never ) ? (LooseParameters< Last< Parameters< EmitEvents[IfAny< | EmitEvents[EventNames<EmitEvents>] | Last< Parameters< EmitEvents[EventNames<EmitEvents>] > >, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last< Parameters< EmitEvents[keyof EmitEvents & string] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & string] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) >] > > >[0] extends Error ? IfAny< | EmitEvents[EventNames<EmitEvents>] | Last<Parameters<EmitEvents[EventNames<EmitEvents>]>>, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last< Parameters< EmitEvents[keyof EmitEvents & string] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & string] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) > : never) & IfAny< | EmitEvents[EventNames<EmitEvents>] | Last<Parameters<EmitEvents[EventNames<EmitEvents>]>>, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & string] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) > : never >>( ev: Ev, ...args: AllButLast<EventParams<EmitEvents, Ev>>) => Promise<FirstNonErrorArg<Last<EventParams<EmitEvents, Ev>>>>;
Emits an event and waits for an acknowledgement from all clients.
Example 1
try { const responses = await io.timeout(1000).emitWithAck("some-event"); console.log(responses); // one response per client } catch (e) { // some clients did not acknowledge the event in the given delay }
a Promise that will be fulfilled when all clients have acknowledged the event
method except
except: (room: Room | Room[]) => BroadcastOperator<EmitEvents, SocketData>;
Excludes a room when emitting.
Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
// the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room io.except("room-101").emit("foo", "bar");
// with an array of rooms io.except(["room-101", "room-102"]).emit("foo", "bar");
// with multiple chained calls io.except("room-101").except("room-102").emit("foo", "bar");
method fetchSockets
fetchSockets: () => Promise<RemoteSocket<EmitEvents, SocketData>[]>;
Returns the matching socket instances. This method works across a cluster of several Socket.IO servers.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Example 1
// return all Socket instances const sockets = await io.fetchSockets();
// return all Socket instances in the "room1" room const sockets = await io.in("room1").fetchSockets();
for (const socket of sockets) { console.log(socket.id); console.log(socket.handshake); console.log(socket.rooms); console.log(socket.data);
socket.emit("hello"); socket.join("room1"); socket.leave("room2"); socket.disconnect(); }
method in
in: (room: Room | Room[]) => BroadcastOperator<EmitEvents, SocketData>;
Targets a room when emitting. Similar to
to()
, but might feel clearer in some cases:Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
// disconnect all clients in the "room-101" room io.in("room-101").disconnectSockets();
method socketsJoin
socketsJoin: (room: Room | Room[]) => void;
Makes the matching socket instances join the specified rooms.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Parameter room
a room, or an array of rooms
Example 1
// make all socket instances join the "room1" room io.socketsJoin("room1");
// make all socket instances in the "room1" room join the "room2" and "room3" rooms io.in("room1").socketsJoin(["room2", "room3"]);
method socketsLeave
socketsLeave: (room: Room | Room[]) => void;
Makes the matching socket instances leave the specified rooms.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Parameter room
a room, or an array of rooms
Example 1
// make all socket instances leave the "room1" room io.socketsLeave("room1");
// make all socket instances in the "room1" room leave the "room2" and "room3" rooms io.in("room1").socketsLeave(["room2", "room3"]);
method timeout
timeout: ( timeout: number) => BroadcastOperator<DecorateAcknowledgements<EmitEvents>, SocketData>;
Adds a timeout in milliseconds for the next operation
Parameter timeout
Example 1
io.timeout(1000).emit("some-event", (err, responses) => { if (err) { // some clients did not acknowledge the event in the given delay } else { console.log(responses); // one response per client } });
method to
to: (room: Room | Room[]) => BroadcastOperator<EmitEvents, SocketData>;
Targets a room when emitting.
Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
// the “foo” event will be broadcast to all connected clients in the “room-101” room io.to("room-101").emit("foo", "bar");
// with an array of rooms (a client will be notified at most once) io.to(["room-101", "room-102"]).emit("foo", "bar");
// with multiple chained calls io.to("room-101").to("room-102").emit("foo", "bar");
class Namespace
class Namespace< ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents, ServerSideEvents extends EventsMap = DefaultEventsMap, SocketData = any> extends StrictEventEmitter< ServerSideEvents, RemoveAcknowledgements<EmitEvents>, NamespaceReservedEventsMap< ListenEvents, EmitEvents, ServerSideEvents, SocketData >> {}
A Namespace is a communication channel that allows you to split the logic of your application over a single shared connection.
Each namespace has its own:
- event handlers
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
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" namespaceuserNamespace.to("room1").emit("holà");});- middlewares
const orderNamespace = io.of("/orders");orderNamespace.use((socket, next) => {// ensure the socket has access to the "orders" namespace});const userNamespace = io.of("/users");userNamespace.use((socket, next) => {// ensure the socket has access to the "users" namespace});
constructor
constructor( server: Server<ListenEvents, EmitEvents, ServerSideEvents, SocketData>, name: string);
Namespace constructor.
Parameter server
instance
Parameter name
property adapter
adapter: Adapter;
property local
readonly local: BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
Example 1
const myNamespace = io.of("/my-namespace");
// the “foo” event will be broadcast to all connected clients on this node myNamespace.local.emit("foo", "bar");
a new BroadcastOperator instance for chaining
property name
readonly name: string;
property server
readonly server: Server<ListenEvents, EmitEvents, ServerSideEvents, SocketData>;
property sockets
readonly sockets: Map< SocketId, Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>>;
A map of currently connected sockets.
property volatile
readonly volatile: BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).
Example 1
const myNamespace = io.of("/my-namespace");
myNamespace.volatile.emit("hello"); // the clients may or may not receive it
self
method allSockets
allSockets: () => Promise<Set<SocketId>>;
Gets a list of clients.
Deprecated
this method will be removed in the next major release, please use Namespace#serverSideEmit or Namespace#fetchSockets instead.
method compress
compress: ( compress: boolean) => BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Sets the compress flag.
Parameter compress
if
true
, compresses the sending data selfExample 1
const myNamespace = io.of("/my-namespace");
myNamespace.compress(false).emit("hello");
method disconnectSockets
disconnectSockets: (close?: boolean) => void;
Makes the matching socket instances disconnect.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Parameter close
whether to close the underlying connection
Example 1
const myNamespace = io.of("/my-namespace");
// make all socket instances disconnect (the connections might be kept alive for other namespaces) myNamespace.disconnectSockets();
// make all socket instances in the "room1" room disconnect and close the underlying connections myNamespace.in("room1").disconnectSockets(true);
method emit
emit: < Ev extends IfAny< | EmitEvents[EventNames<EmitEvents>] | Last<Parameters<EmitEvents[EventNames<EmitEvents>]>>, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Parameters<EmitEvents[keyof EmitEvents & string]> extends never[] ? keyof EmitEvents & string : never ) ? (Parameters< EmitEvents[keyof EmitEvents & string] > extends never[] ? keyof EmitEvents & string : never) & keyof EmitEvents & string : keyof EmitEvents & string extends ( Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? never : keyof EmitEvents & string ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? never : keyof EmitEvents & string) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Parameters<EmitEvents[keyof EmitEvents & symbol]> extends never[] ? keyof EmitEvents & symbol : never ) ? (Parameters< EmitEvents[keyof EmitEvents & symbol] > extends never[] ? keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : keyof EmitEvents & symbol extends ( Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? never : keyof EmitEvents & symbol ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? never : keyof EmitEvents & symbol) & keyof EmitEvents & symbol : never) >>( ev: Ev, ...args: EventParams<EmitEvents, Ev>) => boolean;
Emits to all connected clients.
Example 1
const myNamespace = io.of("/my-namespace");
myNamespace.emit("hello", "world");
// all serializable datastructures are supported (no need to call JSON.stringify) myNamespace.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
// with an acknowledgement from the clients myNamespace.timeout(1000).emit("some-event", (err, responses) => { if (err) { // some clients did not acknowledge the event in the given delay } else { console.log(responses); // one response per client } });
Always true
method except
except: ( room: Room | Room[]) => BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Excludes a room when emitting.
Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
const myNamespace = io.of("/my-namespace");
// the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room myNamespace.except("room-101").emit("foo", "bar");
// with an array of rooms myNamespace.except(["room-101", "room-102"]).emit("foo", "bar");
// with multiple chained calls myNamespace.except("room-101").except("room-102").emit("foo", "bar");
method fetchSockets
fetchSockets: () => Promise< import('./broadcast-operator').RemoteSocket<EmitEvents, SocketData>[]>;
Returns the matching socket instances.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Example 1
const myNamespace = io.of("/my-namespace");
// return all Socket instances const sockets = await myNamespace.fetchSockets();
// return all Socket instances in the "room1" room const sockets = await myNamespace.in("room1").fetchSockets();
for (const socket of sockets) { console.log(socket.id); console.log(socket.handshake); console.log(socket.rooms); console.log(socket.data);
socket.emit("hello"); socket.join("room1"); socket.leave("room2"); socket.disconnect(); }
method in
in: ( room: Room | Room[]) => BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Targets a room when emitting. Similar to
to()
, but might feel clearer in some cases:Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
const myNamespace = io.of("/my-namespace");
// disconnect all clients in the "room-101" room myNamespace.in("room-101").disconnectSockets();
method send
send: (...args: EventParams<EmitEvents, 'message'>) => this;
Sends a
message
event to all clients.This method mimics the WebSocket.send() method.
Example 1
const myNamespace = io.of("/my-namespace");
myNamespace.send("hello");
// this is equivalent to myNamespace.emit("message", "hello");
self
See Also
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
method serverSideEmit
serverSideEmit: <Ev extends EventNames<ServerSideEvents>>( ev: Ev, ...args: EventParams< DecorateAcknowledgementsWithTimeoutAndMultipleResponses<ServerSideEvents>, Ev >) => boolean;
Sends a message to the other Socket.IO servers of the cluster.
Parameter ev
the event name
Parameter args
an array of arguments, which may include an acknowledgement callback at the end
Example 1
const myNamespace = io.of("/my-namespace");
myNamespace.serverSideEmit("hello", "world");
myNamespace.on("hello", (arg1) => { console.log(arg1); // prints "world" });
// acknowledgements (without binary content) are supported too: myNamespace.serverSideEmit("ping", (err, responses) => { if (err) { // some servers did not acknowledge the event in the given delay } else { console.log(responses); // one response per server (except the current one) } });
myNamespace.on("ping", (cb) => { cb("pong"); });
method serverSideEmitWithAck
serverSideEmitWithAck: < Ev extends IfAny< | ServerSideEvents[EventNames<ServerSideEvents>] | Last<Parameters<ServerSideEvents[EventNames<ServerSideEvents>]>>, EventNames<ServerSideEvents>, | (keyof ServerSideEvents & string extends ( Last< Parameters<ServerSideEvents[keyof ServerSideEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< ServerSideEvents[keyof ServerSideEvents & string] > > > extends void ? never : keyof ServerSideEvents & string : never ) ? (Last< Parameters<ServerSideEvents[keyof ServerSideEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< ServerSideEvents[keyof ServerSideEvents & string] > > > extends void ? never : keyof ServerSideEvents & string : never) & keyof ServerSideEvents & string : never) | (keyof ServerSideEvents & symbol extends ( Last< Parameters<ServerSideEvents[keyof ServerSideEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< ServerSideEvents[keyof ServerSideEvents & symbol] > > > extends void ? never : keyof ServerSideEvents & symbol : never ) ? (Last< Parameters<ServerSideEvents[keyof ServerSideEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< ServerSideEvents[keyof ServerSideEvents & symbol] > > > extends void ? never : keyof ServerSideEvents & symbol : never) & keyof ServerSideEvents & symbol : never) >>( ev: Ev, ...args: AllButLast<EventParams<ServerSideEvents, Ev>>) => Promise<FirstNonErrorArg<Last<EventParams<ServerSideEvents, Ev>>>[]>;
Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster.
Parameter ev
the event name
Parameter args
an array of arguments
a Promise that will be fulfilled when all servers have acknowledged the event
Example 1
const myNamespace = io.of("/my-namespace");
try { const responses = await myNamespace.serverSideEmitWithAck("ping"); console.log(responses); // one response per server (except the current one) } catch (e) { // some servers did not acknowledge the event in the given delay }
method socketsJoin
socketsJoin: (room: Room | Room[]) => void;
Makes the matching socket instances join the specified rooms.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Parameter room
a room, or an array of rooms
Example 1
const myNamespace = io.of("/my-namespace");
// make all socket instances join the "room1" room myNamespace.socketsJoin("room1");
// make all socket instances in the "room1" room join the "room2" and "room3" rooms myNamespace.in("room1").socketsJoin(["room2", "room3"]);
method socketsLeave
socketsLeave: (room: Room | Room[]) => void;
Makes the matching socket instances leave the specified rooms.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Parameter room
a room, or an array of rooms
Example 1
const myNamespace = io.of("/my-namespace");
// make all socket instances leave the "room1" room myNamespace.socketsLeave("room1");
// make all socket instances in the "room1" room leave the "room2" and "room3" rooms myNamespace.in("room1").socketsLeave(["room2", "room3"]);
method timeout
timeout: ( timeout: number) => BroadcastOperator< import('./typed-events').DecorateAcknowledgements< DecorateAcknowledgementsWithMultipleResponses<EmitEvents> >, SocketData>;
Adds a timeout in milliseconds for the next operation.
Parameter timeout
Example 1
const myNamespace = io.of("/my-namespace");
myNamespace.timeout(1000).emit("some-event", (err, responses) => { if (err) { // some clients did not acknowledge the event in the given delay } else { console.log(responses); // one response per client } });
method to
to: ( room: Room | Room[]) => BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Targets a room when emitting.
Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
const myNamespace = io.of("/my-namespace");
// the “foo” event will be broadcast to all connected clients in the “room-101” room myNamespace.to("room-101").emit("foo", "bar");
// with an array of rooms (a client will be notified at most once) myNamespace.to(["room-101", "room-102"]).emit("foo", "bar");
// with multiple chained calls myNamespace.to("room-101").to("room-102").emit("foo", "bar");
method use
use: ( fn: ( socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>, next: (err?: ExtendedError) => void ) => void) => this;
Registers a middleware, which is a function that gets executed for every incoming Socket.
Parameter fn
the middleware function
Example 1
const myNamespace = io.of("/my-namespace");
myNamespace.use((socket, next) => { // ... next(); });
method write
write: (...args: EventParams<EmitEvents, 'message'>) => this;
Sends a
message
event to all clients. Sends amessage
event. Alias of send.self
class RemoteSocket
class RemoteSocket<EmitEvents extends EventsMap, SocketData> implements TypedEventBroadcaster<EmitEvents> {}
Expose of subset of the attributes and methods of the Socket class
constructor
constructor(adapter: Adapter, details: SocketDetails<SocketData>);
property data
readonly data: {};
property handshake
readonly handshake: Handshake;
property id
readonly id: SocketId;
property rooms
readonly rooms: Set<Room>;
method disconnect
disconnect: (close?: boolean) => this;
Disconnects this client.
Parameter close
if
true
, closes the underlying connection {Socket} self
method emit
emit: <Ev extends EventNames<EmitEvents>>( ev: Ev, ...args: EventParams<EmitEvents, Ev>) => boolean;
method join
join: (room: Room | Room[]) => void;
Joins a room.
Parameter room
room or array of rooms
method leave
leave: (room: Room) => void;
Leaves a room.
Parameter room
method timeout
timeout: ( timeout: number) => BroadcastOperator<DecorateAcknowledgements<EmitEvents>, SocketData>;
Adds a timeout in milliseconds for the next operation.
Parameter timeout
Example 1
const sockets = await io.fetchSockets();
for (const socket of sockets) { if (someCondition) { socket.timeout(1000).emit("some-event", (err) => { if (err) { // the client did not acknowledge the event in the given delay } }); } }
// note: if possible, using a room instead of looping over all sockets is preferable io.timeout(1000).to(someConditionRoom).emit("some-event", (err, responses) => { // ... });
class Server
class Server< ListenEvents extends EventsMap = DefaultEventsMap, /** * Types for the events sent to the clients. * * @example * interface ServerToClientEvents { * hello: (arg: string) => void; * } * * const io = new Server<DefaultEventMap, ServerToClientEvents>(); * * io.emit("hello", "world"); */ EmitEvents extends EventsMap = ListenEvents, /** * Types for the events received from and sent to the other servers. * * @example * interface InterServerEvents { * ping: (arg: number) => void; * } * * const io = new Server<DefaultEventMap, DefaultEventMap, ServerToClientEvents>(); * * io.serverSideEmit("ping", 123); * * io.on("ping", (arg) => { * // `arg` is inferred as number * }); */ ServerSideEvents extends EventsMap = DefaultEventsMap, /** * Additional properties that can be attached to the socket instance. * * Note: any property can be attached directly to the socket instance (`socket.foo = "bar"`), but the `data` object * will be included when calling {@link Server#fetchSockets}. * * @example * io.on("connection", (socket) => { * socket.data.eventsCount = 0; * * socket.onAny(() => { * socket.data.eventsCount++; * }); * }); */ SocketData = any> extends StrictEventEmitter< ServerSideEvents, RemoveAcknowledgements<EmitEvents>, ServerReservedEventsMap<ListenEvents, EmitEvents, ServerSideEvents, SocketData>> {}
Represents a Socket.IO server.
Example 1
import { Server } from "socket.io";
const io = new Server();
io.on("connection", (socket) => { console.log(
socket ${socket.id} connected
);// send an event to the client socket.emit("foo", "bar");
socket.on("foobar", () => { // an event was received from the client });
// upon disconnection socket.on("disconnect", (reason) => { console.log(
socket ${socket.id} disconnected due to ${reason}
); }); });io.listen(3000);
constructor
constructor(opts?: Partial<ServerOptions>);
Server constructor.
Parameter srv
http server, port, or options
Parameter opts
constructor
constructor(srv?: any, opts?: Partial<ServerOptions>);
constructor
constructor(srv: any, opts?: Partial<ServerOptions>);
property encoder
readonly encoder: Encoder;
property engine
engine: Engine;
A reference to the underlying Engine.IO server.
Example 1
const clientsCount = io.engine.clientsCount;
property httpServer
httpServer: any;
The underlying Node.js HTTP server.
See Also
https://nodejs.org/api/http.html
property local
readonly local: BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
Example 1
// the “foo” event will be broadcast to all connected clients on this node io.local.emit("foo", "bar");
a new BroadcastOperator instance for chaining
property sockets
readonly sockets: Namespace< ListenEvents, EmitEvents, ServerSideEvents, SocketData>;
property volatile
readonly volatile: BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).
Example 1
io.volatile.emit("hello"); // the clients may or may not receive it
a new BroadcastOperator instance for chaining
method adapter
adapter: { (): AdapterConstructor | undefined; (v: any): this };
Sets the adapter for rooms.
Parameter v
pathname self when setting or value when getting
method allSockets
allSockets: () => Promise<Set<SocketId>>;
Gets a list of socket ids.
Deprecated
this method will be removed in the next major release, please use Server#serverSideEmit or Server#fetchSockets instead.
method attach
attach: (srv: TServerInstance | number, opts?: Partial<ServerOptions>) => this;
Attaches socket.io to a server or port.
Parameter srv
server or port
Parameter opts
options passed to engine.io self
method attachApp
attachApp: (app: any, opts?: Partial<ServerOptions>) => void;
method bind
bind: (engine: any) => this;
Binds socket.io to an engine.io instance.
Parameter engine
engine.io (or compatible) server self
method close
close: (fn?: (err?: Error) => void) => Promise<void>;
Closes server connection
Parameter fn
optional, called as
fn([err])
on error OR all conns closed
method compress
compress: ( compress: boolean) => BroadcastOperator< import('./typed-events').DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Sets the compress flag.
Parameter compress
if
true
, compresses the sending data a new BroadcastOperator instance for chainingExample 1
io.compress(false).emit("hello");
method connectTimeout
connectTimeout: { (v: number): this; (): number; (v?: number): number | this };
Set the delay after which a client without namespace is closed
Parameter v
method disconnectSockets
disconnectSockets: (close?: boolean) => void;
Makes the matching socket instances disconnect.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Parameter close
whether to close the underlying connection
Example 1
// make all socket instances disconnect (the connections might be kept alive for other namespaces) io.disconnectSockets();
// make all socket instances in the "room1" room disconnect and close the underlying connections io.in("room1").disconnectSockets(true);
method except
except: ( room: Room | Room[]) => BroadcastOperator< import('./typed-events').DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Excludes a room when emitting.
Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
// the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room io.except("room-101").emit("foo", "bar");
// with an array of rooms io.except(["room-101", "room-102"]).emit("foo", "bar");
// with multiple chained calls io.except("room-101").except("room-102").emit("foo", "bar");
method fetchSockets
fetchSockets: () => Promise<RemoteSocket<EmitEvents, SocketData>[]>;
Returns the matching socket instances.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Example 1
// return all Socket instances const sockets = await io.fetchSockets();
// return all Socket instances in the "room1" room const sockets = await io.in("room1").fetchSockets();
for (const socket of sockets) { console.log(socket.id); console.log(socket.handshake); console.log(socket.rooms); console.log(socket.data);
socket.emit("hello"); socket.join("room1"); socket.leave("room2"); socket.disconnect(); }
method in
in: ( room: Room | Room[]) => BroadcastOperator< import('./typed-events').DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Targets a room when emitting. Similar to
to()
, but might feel clearer in some cases:Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
// disconnect all clients in the "room-101" room io.in("room-101").disconnectSockets();
method listen
listen: (srv: TServerInstance | number, opts?: Partial<ServerOptions>) => this;
Attaches socket.io to a server or port.
Parameter srv
server or port
Parameter opts
options passed to engine.io self
method of
of: ( name: string | RegExp | ParentNspNameMatchFn, fn?: ( socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData> ) => void) => Namespace<ListenEvents, EmitEvents, ServerSideEvents, SocketData>;
Looks up a namespace.
Parameter name
nsp name
Parameter fn
optional, nsp
connection
ev handlerExample 1
// with a simple string const myNamespace = io.of("/my-namespace");
// with a regex const dynamicNsp = io.of(/^/dynamic-\d+$/).on("connection", (socket) => { const namespace = socket.nsp; // newNamespace.name === "/dynamic-101"
// broadcast to all clients in the given sub-namespace namespace.emit("hello"); });
method path
path: { (v: string): this; (): string; (v?: string): string | this };
Sets the client serving path.
Parameter v
pathname {Server|String} self when setting or value when getting
method send
send: (...args: EventParams<EmitEvents, 'message'>) => this;
Sends a
message
event to all clients.This method mimics the WebSocket.send() method.
Example 1
io.send("hello");
// this is equivalent to io.emit("message", "hello");
self
See Also
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
method serveClient
serveClient: { (v: boolean): this; (): boolean; (v?: boolean): boolean | this };
Sets/gets whether client code is being served.
Parameter v
whether to serve client code self when setting or value when getting
method serverSideEmit
serverSideEmit: <Ev extends EventNames<ServerSideEvents>>( ev: Ev, ...args: EventParams< DecorateAcknowledgementsWithTimeoutAndMultipleResponses<ServerSideEvents>, Ev >) => boolean;
Sends a message to the other Socket.IO servers of the cluster.
Parameter ev
the event name
Parameter args
an array of arguments, which may include an acknowledgement callback at the end
Example 1
io.serverSideEmit("hello", "world");
io.on("hello", (arg1) => { console.log(arg1); // prints "world" });
// acknowledgements (without binary content) are supported too: io.serverSideEmit("ping", (err, responses) => { if (err) { // some servers did not acknowledge the event in the given delay } else { console.log(responses); // one response per server (except the current one) } });
io.on("ping", (cb) => { cb("pong"); });
method serverSideEmitWithAck
serverSideEmitWithAck: < Ev extends IfAny< | ServerSideEvents[EventNames<ServerSideEvents>] | Last<Parameters<ServerSideEvents[EventNames<ServerSideEvents>]>>, EventNames<ServerSideEvents>, | (keyof ServerSideEvents & string extends ( Last< Parameters<ServerSideEvents[keyof ServerSideEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< ServerSideEvents[keyof ServerSideEvents & string] > > > extends void ? never : keyof ServerSideEvents & string : never ) ? (Last< Parameters<ServerSideEvents[keyof ServerSideEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< ServerSideEvents[keyof ServerSideEvents & string] > > > extends void ? never : keyof ServerSideEvents & string : never) & keyof ServerSideEvents & string : never) | (keyof ServerSideEvents & symbol extends ( Last< Parameters<ServerSideEvents[keyof ServerSideEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< ServerSideEvents[keyof ServerSideEvents & symbol] > > > extends void ? never : keyof ServerSideEvents & symbol : never ) ? (Last< Parameters<ServerSideEvents[keyof ServerSideEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< ServerSideEvents[keyof ServerSideEvents & symbol] > > > extends void ? never : keyof ServerSideEvents & symbol : never) & keyof ServerSideEvents & symbol : never) >>( ev: Ev, ...args: AllButLast<EventParams<ServerSideEvents, Ev>>) => Promise<FirstNonErrorArg<Last<EventParams<ServerSideEvents, Ev>>>[]>;
Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster.
Parameter ev
the event name
Parameter args
an array of arguments
a Promise that will be fulfilled when all servers have acknowledged the event
Example 1
try { const responses = await io.serverSideEmitWithAck("ping"); console.log(responses); // one response per server (except the current one) } catch (e) { // some servers did not acknowledge the event in the given delay }
method socketsJoin
socketsJoin: (room: Room | Room[]) => void;
Makes the matching socket instances join the specified rooms.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Parameter room
a room, or an array of rooms
Example 1
// make all socket instances join the "room1" room io.socketsJoin("room1");
// make all socket instances in the "room1" room join the "room2" and "room3" rooms io.in("room1").socketsJoin(["room2", "room3"]);
method socketsLeave
socketsLeave: (room: Room | Room[]) => void;
Makes the matching socket instances leave the specified rooms.
Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible Adapter.
Parameter room
a room, or an array of rooms
Example 1
// make all socket instances leave the "room1" room io.socketsLeave("room1");
// make all socket instances in the "room1" room leave the "room2" and "room3" rooms io.in("room1").socketsLeave(["room2", "room3"]);
method timeout
timeout: ( timeout: number) => BroadcastOperator< import('./typed-events').DecorateAcknowledgements< import('./typed-events').DecorateAcknowledgementsWithMultipleResponses<EmitEvents> >, SocketData>;
Adds a timeout in milliseconds for the next operation.
Parameter timeout
Example 1
io.timeout(1000).emit("some-event", (err, responses) => { if (err) { // some clients did not acknowledge the event in the given delay } else { console.log(responses); // one response per client } });
method to
to: ( room: Room | Room[]) => BroadcastOperator< import('./typed-events').DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Targets a room when emitting.
Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
// the “foo” event will be broadcast to all connected clients in the “room-101” room io.to("room-101").emit("foo", "bar");
// with an array of rooms (a client will be notified at most once) io.to(["room-101", "room-102"]).emit("foo", "bar");
// with multiple chained calls io.to("room-101").to("room-102").emit("foo", "bar");
method use
use: ( fn: ( socket: Socket<ListenEvents, EmitEvents, ServerSideEvents, SocketData>, next: (err?: ExtendedError) => void ) => void) => this;
Registers a middleware, which is a function that gets executed for every incoming Socket.
Parameter fn
the middleware function
Example 1
io.use((socket, next) => { // ... next(); });
method write
write: (...args: EventParams<EmitEvents, 'message'>) => this;
Sends a
message
event to all clients. Alias of send.self
class Socket
class Socket< ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents, ServerSideEvents extends EventsMap = DefaultEventsMap, SocketData = any> extends StrictEventEmitter<ListenEvents, EmitEvents, SocketReservedEventsMap> {}
This is the main object for interacting with a client.
A Socket belongs to a given Namespace and uses an underlying Client to communicate.
Within each Namespace, you can also define arbitrary channels (called "rooms") that the Socket can join and leave. That provides a convenient way to broadcast to a group of socket instances.
Example 1
io.on("connection", (socket) => { console.log(
socket ${socket.id} connected
);// send an event to the client socket.emit("foo", "bar");
socket.on("foobar", () => { // an event was received from the client });
// join the room named "room1" socket.join("room1");
// broadcast to everyone in the room named "room1" io.to("room1").emit("hello");
// upon disconnection socket.on("disconnect", (reason) => { console.log(
socket ${socket.id} disconnected due to ${reason}
); }); });
constructor
constructor( nsp: Namespace<ListenEvents, EmitEvents, ServerSideEvents, any>, client: Client<ListenEvents, EmitEvents, ServerSideEvents, any>, auth: Record<string, unknown>, previousSession?: Session);
Interface to a
Client
for a givenNamespace
.Parameter nsp
Parameter client
Parameter auth
property broadcast
readonly broadcast: BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the sender.
Example 1
io.on("connection", (socket) => { // the “foo” event will be broadcast to all connected clients, except this socket socket.broadcast.emit("foo", "bar"); });
a new BroadcastOperator instance for chaining
property client
readonly client: Client<ListenEvents, EmitEvents, ServerSideEvents, any>;
property conn
readonly conn: any;
A reference to the underlying Client transport connection (Engine.IO Socket object).
Example 1
io.on("connection", (socket) => { console.log(socket.conn.transport.name); // prints "polling" or "websocket"
socket.conn.once("upgrade", () => { console.log(socket.conn.transport.name); // prints "websocket" }); });
property connected
connected: boolean;
Whether the socket is currently connected or not.
Example 1
io.use((socket, next) => { console.log(socket.connected); // false next(); });
io.on("connection", (socket) => { console.log(socket.connected); // true });
property data
data: {};
Additional information that can be attached to the Socket instance and which will be used in the method.
property disconnected
readonly disconnected: boolean;
Whether the socket is currently disconnected
property handshake
readonly handshake: Handshake;
The handshake details.
property id
readonly id: SocketId;
An unique identifier for the session.
property local
readonly local: BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
Example 1
io.on("connection", (socket) => { // the “foo” event will be broadcast to all connected clients on this node, except this socket socket.local.emit("foo", "bar"); });
a new BroadcastOperator instance for chaining
property nsp
readonly nsp: Namespace<ListenEvents, EmitEvents, ServerSideEvents, any>;
property recovered
readonly recovered: boolean;
Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will be transmitted to the client, the data attribute and the rooms will be restored.
property request
readonly request: IncomingMessage;
A reference to the request that originated the underlying Engine.IO Socket.
property rooms
readonly rooms: Set<Room>;
Returns the rooms the socket is currently in.
Example 1
io.on("connection", (socket) => { console.log(socket.rooms); // Set { <socket.id> }
socket.join("room1");
console.log(socket.rooms); // Set { <socket.id>, "room1" } });
property volatile
readonly volatile: Socket< ListenEvents, EmitEvents, ServerSideEvents, SocketData>;
Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).
Example 1
io.on("connection", (socket) => { socket.volatile.emit("hello"); // the client may or may not receive it });
{Socket} self
method compress
compress: (compress: boolean) => this;
Sets the compress flag.
Parameter compress
if
true
, compresses the sending data {Socket} selfExample 1
io.on("connection", (socket) => { socket.compress(false).emit("hello"); });
method disconnect
disconnect: (close?: boolean) => this;
Disconnects this client.
Parameter close
if
true
, closes the underlying connection selfExample 1
io.on("connection", (socket) => { // disconnect this socket (the connection might be kept alive for other namespaces) socket.disconnect();
// disconnect this socket and close the underlying connection socket.disconnect(true); })
method emit
emit: <Ev extends EventNames<EmitEvents>>( ev: Ev, ...args: EventParams<EmitEvents, Ev>) => boolean;
Emits to this client.
Example 1
io.on("connection", (socket) => { socket.emit("hello", "world");
// all serializable datastructures are supported (no need to call JSON.stringify) socket.emit("hello", 1, "2", { 3: ["4"], 5: Buffer.from([6]) });
// with an acknowledgement from the client socket.emit("hello", "world", (val) => { // ... }); });
Always returns
true
.
method emitWithAck
emitWithAck: < Ev extends IfAny< | EmitEvents[EventNames<EmitEvents>] | Last<Parameters<EmitEvents[EventNames<EmitEvents>]>>, EventNames<EmitEvents>, | (keyof EmitEvents & string extends ( Last<Parameters<EmitEvents[keyof EmitEvents & string]>> extends ( ...args: any[] ) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters<EmitEvents[keyof EmitEvents & string]> > > extends void ? never : keyof EmitEvents & string : never ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & string]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & string] > > > extends void ? never : keyof EmitEvents & string : never) & keyof EmitEvents & string : never) | (keyof EmitEvents & symbol extends ( Last<Parameters<EmitEvents[keyof EmitEvents & symbol]>> extends ( ...args: any[] ) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > > extends void ? never : keyof EmitEvents & symbol : never ) ? (Last< Parameters<EmitEvents[keyof EmitEvents & symbol]> > extends (...args: any[]) => any ? FirstNonErrorArg< ((...args: any[]) => any) & Last< Parameters< EmitEvents[keyof EmitEvents & symbol] > > > extends void ? never : keyof EmitEvents & symbol : never) & keyof EmitEvents & symbol : never) >>( ev: Ev, ...args: AllButLast<EventParams<EmitEvents, Ev>>) => Promise<FirstNonErrorArg<Last<EventParams<EmitEvents, Ev>>>>;
Emits an event and waits for an acknowledgement
Example 1
io.on("connection", async (socket) => { // without timeout const response = await socket.emitWithAck("hello", "world");
// with a specific timeout try { const response = await socket.timeout(1000).emitWithAck("hello", "world"); } catch (err) { // the client did not acknowledge the event in the given delay } });
a Promise that will be fulfilled when the client acknowledges the event
method except
except: ( room: Room | Room[]) => BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Excludes a room when broadcasting.
Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
io.on("connection", (socket) => { // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room // and this socket socket.except("room-101").emit("foo", "bar");
// with an array of rooms socket.except(["room-101", "room-102"]).emit("foo", "bar");
// with multiple chained calls socket.except("room-101").except("room-102").emit("foo", "bar"); });
method in
in: ( room: Room | Room[]) => BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Targets a room when broadcasting. Similar to
to()
, but might feel clearer in some cases:Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
io.on("connection", (socket) => { // disconnect all clients in the "room-101" room, except this socket socket.in("room-101").disconnectSockets(); });
method join
join: (rooms: Room | Array<Room>) => Promise<void> | void;
Joins a room.
Parameter rooms
room or array of rooms a Promise or nothing, depending on the adapter
Example 1
io.on("connection", (socket) => { // join a single room socket.join("room1");
// join multiple rooms socket.join(["room1", "room2"]); });
method leave
leave: (room: string) => Promise<void> | void;
Leaves a room.
Parameter room
a Promise or nothing, depending on the adapter
Example 1
io.on("connection", (socket) => { // leave a single room socket.leave("room1");
// leave multiple rooms socket.leave("room1").leave("room2"); });
method listenersAny
listenersAny: () => ((...args: any[]) => void)[];
Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, e.g. to remove listeners.
method listenersAnyOutgoing
listenersAnyOutgoing: () => ((...args: any[]) => void)[];
Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, e.g. to remove listeners.
method offAny
offAny: (listener?: (...args: any[]) => void) => this;
Removes the listener that will be fired when any event is received.
Parameter listener
Example 1
io.on("connection", (socket) => { const catchAllListener = (event, ...args) => { console.log(
got event ${event}
); }socket.onAny(catchAllListener);
// remove a specific listener socket.offAny(catchAllListener);
// or remove all listeners socket.offAny(); });
method offAnyOutgoing
offAnyOutgoing: (listener?: (...args: any[]) => void) => this;
Removes the listener that will be fired when any event is sent.
Parameter listener
the catch-all listener
Example 1
io.on("connection", (socket) => { const catchAllListener = (event, ...args) => { console.log(
sent event ${event}
); }socket.onAnyOutgoing(catchAllListener);
// remove a specific listener socket.offAnyOutgoing(catchAllListener);
// or remove all listeners socket.offAnyOutgoing(); });
method onAny
onAny: (listener: (...args: any[]) => void) => this;
Adds a listener that will be fired when any event is received. The event name is passed as the first argument to the callback.
Parameter listener
Example 1
io.on("connection", (socket) => { socket.onAny((event, ...args) => { console.log(
got event ${event}
); }); });
method onAnyOutgoing
onAnyOutgoing: (listener: (...args: any[]) => void) => this;
Adds a listener that will be fired when any event is sent. The event name is passed as the first argument to the callback.
Note: acknowledgements sent to the client are not included.
Parameter listener
Example 1
io.on("connection", (socket) => { socket.onAnyOutgoing((event, ...args) => { console.log(
sent event ${event}
); }); });
method prependAny
prependAny: (listener: (...args: any[]) => void) => this;
Adds a listener that will be fired when any event is received. The event name is passed as the first argument to the callback. The listener is added to the beginning of the listeners array.
Parameter listener
method prependAnyOutgoing
prependAnyOutgoing: (listener: (...args: any[]) => void) => this;
Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the callback. The listener is added to the beginning of the listeners array.
Parameter listener
Example 1
io.on("connection", (socket) => { socket.prependAnyOutgoing((event, ...args) => { console.log(
sent event ${event}
); }); });
method send
send: (...args: EventParams<EmitEvents, 'message'>) => this;
Sends a
message
event.This method mimics the WebSocket.send() method.
Example 1
io.on("connection", (socket) => { socket.send("hello");
// this is equivalent to socket.emit("message", "hello"); });
self
See Also
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
method timeout
timeout: ( timeout: number) => Socket< ListenEvents, DecorateAcknowledgements<EmitEvents>, ServerSideEvents, SocketData>;
Sets a modifier for a subsequent event emission that the callback will be called with an error when the given number of milliseconds have elapsed without an acknowledgement from the client:
Returns
self
Example 1
io.on("connection", (socket) => { socket.timeout(5000).emit("my-event", (err) => { if (err) { // the client did not acknowledge the event in the given delay } }); });
method to
to: ( room: Room | Room[]) => BroadcastOperator< DecorateAcknowledgementsWithMultipleResponses<EmitEvents>, SocketData>;
Targets a room when broadcasting.
Parameter room
a room, or an array of rooms a new BroadcastOperator instance for chaining
Example 1
io.on("connection", (socket) => { // the “foo” event will be broadcast to all connected clients in the “room-101” room, except this socket socket.to("room-101").emit("foo", "bar");
// the code above is equivalent to: io.to("room-101").except(socket.id).emit("foo", "bar");
// with an array of rooms (a client will be notified at most once) socket.to(["room-101", "room-102"]).emit("foo", "bar");
// with multiple chained calls socket.to("room-101").to("room-102").emit("foo", "bar"); });
method use
use: (fn: (event: Event, next: (err?: Error) => void) => void) => this;
Sets up socket middleware.
Parameter fn
middleware function (event, next) {Socket} self
Example 1
io.on("connection", (socket) => { socket.use(([event, ...args], next) => { if (isUnauthorized(event)) { return next(new Error("unauthorized event")); } // do not forget to call next next(); });
socket.on("error", (err) => { if (err && err.message === "unauthorized event") { socket.disconnect(); } }); });
method write
write: (...args: EventParams<EmitEvents, 'message'>) => this;
Sends a
message
event. Alias of send.self
Interfaces
interface DefaultEventsMap
interface DefaultEventsMap {}
The default events map, used if no EventsMap is given. Using this EventsMap is equivalent to accepting all event names, and any data.
index signature
[event: string]: (...args: any[]) => void;
interface ExtendedError
interface ExtendedError extends Error {}
property data
data?: any;
interface ServerOptions
interface ServerOptions extends EngineOptions, AttachOptions {}
property adapter
adapter: AdapterConstructor;
the adapter to use the in-memory adapter (https://github.com/socketio/socket.io-adapter)
property cleanupEmptyChildNamespaces
cleanupEmptyChildNamespaces: boolean;
Whether to remove child namespaces that have no sockets connected to them false
property connectionStateRecovery
connectionStateRecovery: { /** * The backup duration of the sessions and the packets. * * @default 120000 (2 minutes) */ maxDisconnectionDuration?: number; /** * Whether to skip middlewares upon successful connection state recovery. * * @default true */ skipMiddlewares?: boolean;};
Whether to enable the recovery of connection state when a client temporarily disconnects.
The connection state includes the missed packets, the rooms the socket was in and the
data
attribute.
property connectTimeout
connectTimeout: number;
how many ms before a client without namespace is closed 45000
property parser
parser: any;
the parser to use the default parser (https://github.com/socketio/socket.io-parser)
property path
path: string;
name of the path to capture "/socket.io"
property serveClient
serveClient: boolean;
whether to serve the client files true
Type Aliases
type DisconnectReason
type DisconnectReason = | 'transport error' | 'transport close' | 'forced close' | 'ping timeout' | 'parse error' | 'server shutting down' | 'forced server close' | 'client namespace disconnect' | 'server namespace disconnect';
type Event
type Event = [string, ...any[]];
[eventName, ...args]
Package Files (6)
Dependencies (7)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/socket.io
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/socket.io)
- HTML<a href="https://www.jsdocs.io/package/socket.io"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 7227 ms. - Missing or incorrect documentation? Open an issue for this package.