socket.io-client
- Version 4.8.1
- Published
- 1.41 MB
- 4 dependencies
- MIT license
Install
npm i socket.io-client
yarn add socket.io-client
pnpm add socket.io-client
Overview
Realtime application framework client
Index
Functions
Classes
Interfaces
Namespaces
Functions
function connect
connect: { (opts?: Partial<ManagerOptions & SocketOptions>): Socket; (uri?: string, opts?: Partial<ManagerOptions & SocketOptions>): Socket< DefaultEventsMap, DefaultEventsMap >;};
Looks up an existing
Manager
for multiplexing. If the user summons:io('http://localhost/a');
io('http://localhost/b');
We reuse the existing instance based on same scheme/port/host, and we initialize sockets for each namespace.
Modifiers
@public
function io
io: { (opts?: Partial<ManagerOptions & SocketOptions>): Socket; (uri?: string, opts?: Partial<ManagerOptions & SocketOptions>): Socket< DefaultEventsMap, DefaultEventsMap >;};
Looks up an existing
Manager
for multiplexing. If the user summons:io('http://localhost/a');
io('http://localhost/b');
We reuse the existing instance based on same scheme/port/host, and we initialize sockets for each namespace.
Modifiers
@public
function lookup
lookup: { (opts?: Partial<ManagerOptions & SocketOptions>): Socket; (uri?: string, opts?: Partial<ManagerOptions & SocketOptions>): Socket< DefaultEventsMap, DefaultEventsMap >;};
Looks up an existing
Manager
for multiplexing. If the user summons:io('http://localhost/a');
io('http://localhost/b');
We reuse the existing instance based on same scheme/port/host, and we initialize sockets for each namespace.
Modifiers
@public
Classes
class Manager
class Manager< ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<{}, {}, ManagerReservedEvents> {}
constructor
constructor(opts: Partial<ManagerOptions>);
Manager
constructor.Parameter uri
engine instance or engine uri/opts
Parameter opts
options
Modifiers
@public
constructor
constructor(uri?: string, opts?: Partial<ManagerOptions>);
constructor
constructor( uri?: string | Partial<ManagerOptions>, opts?: Partial<ManagerOptions>);
property engine
engine: Engine;
The Engine.IO client instance
Modifiers
@public
property opts
opts: Partial<ManagerOptions>;
method connect
connect: (fn?: (err?: Error) => void) => this;
Alias for open()
self
Modifiers
@public
method open
open: (fn?: (err?: Error) => void) => this;
Sets the current transport
socket
.Parameter fn
optional, callback self
Modifiers
@public
method randomizationFactor
randomizationFactor: { (v: number): this; (): number; (v?: number): number | this;};
Sets the randomization factor
Parameter v
the randomization factor self or value
Modifiers
@public
method reconnection
reconnection: { (v: boolean): this; (): boolean; (v?: boolean): boolean | this };
Sets the
reconnection
config.Parameter v
true/false if it should automatically reconnect {Manager} self or value
Modifiers
@public
method reconnectionAttempts
reconnectionAttempts: { (v: number): this; (): number; (v?: number): number | this;};
Sets the reconnection attempts config.
Parameter v
max reconnection attempts before giving up {Manager} self or value
Modifiers
@public
method reconnectionDelay
reconnectionDelay: { (v: number): this; (): number; (v?: number): number | this;};
Sets the delay between reconnections.
Parameter v
delay {Manager} self or value
Modifiers
@public
method reconnectionDelayMax
reconnectionDelayMax: { (v: number): this; (): number; (v?: number): number | this;};
Sets the maximum delay between reconnections.
Parameter v
delay self or value
Modifiers
@public
method socket
socket: (nsp: string, opts?: Partial<SocketOptions>) => Socket;
Creates a new socket for the given
nsp
.{Socket}
Modifiers
@public
method timeout
timeout: { (v: number | boolean): this; (): number | boolean; (v?: number | boolean): number | boolean | this;};
Sets the connection timeout.
false
to disableParameter v
connection timeout self or value
Modifiers
@public
class Socket
class Socket< ListenEvents extends EventsMap = DefaultEventsMap, EmitEvents extends EventsMap = ListenEvents> extends Emitter<ListenEvents, EmitEvents, SocketReservedEvents> {}
A Socket is the fundamental class for interacting with the server.
A Socket belongs to a certain Namespace (by default /) and uses an underlying Manager to communicate.
Example 1
const socket = io();
socket.on("connect", () => { console.log("connected"); });
// send an event to the server socket.emit("foo", "bar");
socket.on("foobar", () => { // an event was received from the server });
// upon disconnection socket.on("disconnect", (reason) => { console.log(
disconnected due to ${reason}
); });
constructor
constructor( io: Manager<DefaultEventsMap, DefaultEventsMap>, nsp: string, opts?: Partial<SocketOptions>);
Socket
constructor.
property active
readonly active: boolean;
Whether the Socket will try to reconnect when its Manager connects or reconnects.
Example 1
const socket = io();
console.log(socket.active); // true
socket.on("disconnect", (reason) => { if (reason === "io server disconnect") { // the disconnection was initiated by the server, you need to manually reconnect console.log(socket.active); // false } // else the socket will automatically try to reconnect console.log(socket.active); // true });
property auth
auth: { [key: string]: any } | ((cb: (data: object) => void) => void);
Credentials that are sent when accessing a namespace.
Example 1
const socket = io({ auth: { token: "abcd" } });
// or with a function const socket = io({ auth: (cb) => { cb({ token: localStorage.token }) } });
property connected
connected: boolean;
Whether the socket is currently connected to the server.
Example 1
const socket = io();
socket.on("connect", () => { console.log(socket.connected); // true });
socket.on("disconnect", () => { console.log(socket.connected); // false });
property disconnected
readonly disconnected: boolean;
Whether the socket is currently disconnected
Example 1
const socket = io();
socket.on("connect", () => { console.log(socket.disconnected); // false });
socket.on("disconnect", () => { console.log(socket.disconnected); // true });
property id
id: string;
A unique identifier for the session.
undefined
when the socket is not connected.Example 1
const socket = io();
console.log(socket.id); // undefined
socket.on("connect", () => { console.log(socket.id); // "G5p5..." });
property io
readonly io: Manager<ListenEvents, EmitEvents>;
property receiveBuffer
receiveBuffer: (readonly any[])[];
Buffer for packets received before the CONNECT packet
property recovered
recovered: boolean;
Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will be transmitted by the server.
property sendBuffer
sendBuffer: Packet[];
Buffer for packets that will be sent once the socket is connected
property volatile
readonly volatile: Socket<ListenEvents, EmitEvents>;
Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not ready to send messages.
Returns
self
Example 1
socket.volatile.emit("hello"); // the server may or may not receive it
method close
close: () => this;
Alias for .
self
method compress
compress: (compress: boolean) => this;
Sets the compress flag.
Parameter compress
if
true
, compresses the sending data selfExample 1
socket.compress(false).emit("hello");
method connect
connect: () => this;
"Opens" the socket.
Example 1
const socket = io({ autoConnect: false });
socket.connect();
method disconnect
disconnect: () => this;
Disconnects the socket manually. In that case, the socket will not try to reconnect.
If this is the last active Socket instance of the Manager, the low-level connection will be closed.
Example 1
const socket = io();
socket.on("disconnect", (reason) => { // console.log(reason); prints "io client disconnect" });
socket.disconnect();
self
method emit
emit: <Ev extends EventNames<EmitEvents>>( ev: Ev, ...args: EventParams<EmitEvents, Ev>) => this;
Override
emit
. If the event is inevents
, it's emitted normally.Example 1
socket.emit("hello", "world");
// all serializable datastructures are supported (no need to call JSON.stringify) socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
// with an acknowledgement from the server socket.emit("hello", "world", (val) => { // ... });
self
method emitWithAck
emitWithAck: <Ev extends EventNames<EmitEvents>>( ev: Ev, ...args: AllButLast<EventParams<EmitEvents, Ev>>) => Promise<FirstArg<Last<EventParams<EmitEvents, Ev>>>>;
Emits an event and waits for an acknowledgement
Example 1
// 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 server did not acknowledge the event in the given delay }
a Promise that will be fulfilled when the server acknowledges the event
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 emitted.
Parameter listener
Example 1
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 emitted.
Parameter listener
the catch-all listener (optional)
Example 1
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 emitted. The event name is passed as the first argument to the callback.
Parameter listener
Example 1
socket.onAny((event, ...args) => { console.log(
got ${event}
); });
method onAnyOutgoing
onAnyOutgoing: (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.
Note: acknowledgements sent to the server are not included.
Parameter listener
Example 1
socket.onAnyOutgoing((event, ...args) => { console.log(
sent event ${event}
); });
method open
open: () => this;
Alias for .
method prependAny
prependAny: (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
socket.prependAny((event, ...args) => { console.log(
got event ${event}
); });
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.
Note: acknowledgements sent to the server are not included.
Parameter listener
Example 1
socket.prependAnyOutgoing((event, ...args) => { console.log(
sent event ${event}
); });
method send
send: (...args: any[]) => this;
Sends a
message
event.This method mimics the WebSocket.send() method.
Example 1
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>>;
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 server:
Returns
self
Example 1
socket.timeout(5000).emit("my-event", (err) => { if (err) { // the server did not acknowledge the event in the given delay } });
Interfaces
interface ManagerOptions
interface ManagerOptions extends EngineOptions {}
property autoConnect
autoConnect: boolean;
Should we automatically connect? true
property forceNew
forceNew: boolean;
Should we force a new Manager for this connection? false
property multiplex
multiplex: boolean;
Should we multiplex our connection (reuse existing Manager) ? true
property parser
parser: any;
the parser to use. Defaults to an instance of the Parser that ships with socket.io.
property path
path: string;
The path to get our client file from, in the case of the server serving it '/socket.io'
property randomizationFactor
randomizationFactor: number;
Used in the exponential backoff jitter when reconnecting 0.5
property reconnection
reconnection: boolean;
Should we allow reconnections? true
property reconnectionAttempts
reconnectionAttempts: number;
How many reconnection attempts should we try? Infinity
property reconnectionDelay
reconnectionDelay: number;
The time delay in milliseconds between reconnection attempts 1000
property reconnectionDelayMax
reconnectionDelayMax: number;
The max time delay in milliseconds between reconnection attempts 5000
property timeout
timeout: number;
The timeout in milliseconds for our connection attempt 20000
interface SocketOptions
interface SocketOptions {}
property ackTimeout
ackTimeout?: number;
The default timeout in milliseconds used when waiting for an acknowledgement.
property auth
auth?: | { [key: string]: any; } | ((cb: (data: object) => void) => void);
the authentication payload sent when connecting to the Namespace
property retries
retries?: number;
The maximum number of retries. Above the limit, the packet will be discarded.
Using
Infinity
means the delivery guarantee is "at-least-once" (instead of "at-most-once" by default), but a smaller value like 10 should be sufficient in practice.
Namespaces
namespace Socket
namespace Socket {}
type DisconnectReason
type DisconnectReason = | 'io server disconnect' | 'io client disconnect' | 'ping timeout' | 'transport close' | 'transport error' | 'parse error';
Package Files (3)
Dependencies (4)
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-client
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/socket.io-client)
- HTML<a href="https://www.jsdocs.io/package/socket.io-client"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4607 ms. - Missing or incorrect documentation? Open an issue for this package.