Client API

IO

Exposed as the io namespace in the standalone build, or the result of calling require("socket.io-client").

  1. <script src="/socket.io/socket.io.js"></script>
  2. <script>
  3. const socket = io("http://localhost");
  4. </script>
  1. const io = require("socket.io-client");
  2. // or with import syntax
  3. import { io } from "socket.io-client";

io.protocol

  • (Number)

The protocol revision number (currently: 5).

The protocol defines the format of the packets exchanged between the client and the server. Both the client and the server must use the same revision in order to understand each other.

You can find more information here.

io([url][, options])

  • url (String) (defaults to window.location.host)
  • options (Object)
    • forceNew (Boolean) whether to reuse an existing connection
  • Returns Socket

Creates a new Manager for the given URL, and attempts to reuse an existing Manager for subsequent calls, unless the multiplex option is passed with false. Passing this option is the equivalent of passing "force new connection": true or forceNew: true.

A new Socket instance is returned for the namespace specified by the pathname in the URL, defaulting to /. For example, if the url is http://localhost/users, a transport connection will be established to http://localhost and a Socket.IO connection will be established to /users.

Query parameters can also be provided, either with the query option or directly in the url (example: http://localhost/users?token=abc).

  1. const io = require("socket.io-client");
  2. const socket = io("ws://example.com/my-namespace", {
  3. reconnectionDelayMax: 10000,
  4. auth: {
  5. token: "123"
  6. },
  7. query: {
  8. "my-key": "my-value"
  9. }
  10. });

is the short version of:

  1. const { Manager } = require("socket.io-client");
  2. const manager = new Manager("ws://example.com", {
  3. reconnectionDelayMax: 10000,
  4. query: {
  5. "my-key": "my-value"
  6. }
  7. });
  8. const socket = manager.socket("/my-namespace", {
  9. auth: {
  10. token: "123"
  11. }
  12. });

See new Manager(url[, options]) for the list of available options.

Please note: manager.socket("/my-namespace", options ) will only read the auth key in the options object. query: {…} and other optional values are only used when passed via a new Manager(uri, options) instance.

See Migrating from 2.x to 3.0 for more on the difference between the auth and query options.

Manager

The Manager manages the Engine.IO client instance, which is the low-level engine that establishes the connection to the server (by using transports like WebSocket or HTTP long-polling).

The Manager handles the reconnection logic.

A single Manager can be used by several Sockets. You can find more information about this multiplexing feature here.

Please note that, in most cases, you won’t use the Manager directly but use the Socket instance instead.

new Manager(url[, options])

  • url (String)
  • options (Object)
  • Returns Manager

Available options:

OptionDefault valueDescription
path/socket.ioname of the path that is captured on the server side
reconnectiontruewhether to reconnect automatically
reconnectionAttemptsInfinitynumber of reconnection attempts before giving up
reconnectionDelay1000how long to initially wait before attempting a new reconnection. Affected by +/- randomizationFactor, for example the default initial delay will be between 500 to 1500ms.
reconnectionDelayMax5000maximum amount of time to wait between reconnections. Each attempt increases the reconnection delay by 2x along with a randomization factor.
randomizationFactor0.50 <= randomizationFactor <= 1
timeout20000connection timeout before an error event is emitted
autoConnecttrueby setting this false, you have to call manager.open whenever you decide it’s appropriate
query{}additional query parameters that are sent when connecting a namespace (then found in socket.handshake.query object on the server-side)
parser-the parser to use. Defaults to an instance of the Parser that ships with socket.io. See socket.io-parser.

Available options for the underlying Engine.IO client:

OptionDefault valueDescription
upgradetruewhether the client should try to upgrade the transport from long-polling to something better.
forceJSONPfalseforces JSONP for polling transport.
jsonptruedetermines whether to use JSONP when necessary for polling. If disabled (by settings to false) an error will be emitted (saying “No transports available”) if no other transports are available. If another transport is available for opening a connection (e.g. WebSocket) that transport will be used instead.
forceBase64falseforces base 64 encoding for polling transport even when XHR2 responseType is available and WebSocket even if the used standard supports binary.
enablesXDRfalseenables XDomainRequest for IE8 to avoid loading bar flashing with click sound. default to false because XDomainRequest has a flaw of not sending cookie.
timestampRequests-whether to add the timestamp with each transport request. Note: polling requests are always stamped unless this option is explicitly set to false
timestampParamtthe timestamp parameter
transports[“polling”, “websocket”]a list of transports to try (in order). Engine always attempts to connect directly with the first one, provided the feature detection test for it passes.
transportOptions{}hash of options, indexed by transport name, overriding the common options for the given transport
rememberUpgradefalseIf true and if the previous websocket connection to the server succeeded, the connection attempt will bypass the normal upgrade process and will initially try websocket. A connection attempt following a transport error will use the normal upgrade process. It is recommended you turn this on only when using SSL/TLS connections, or if you know that your network does not block websockets.
onlyBinaryUpgradesfalsewhether transport upgrades should be restricted to transports supporting binary data
requestTimeout0timeout for xhr-polling requests in milliseconds (0) (only for polling transport)
protocols-a list of subprotocols (see MDN reference) (only for websocket transport)

Node.js-only options for the underlying Engine.IO client:

OptionDefault valueDescription
agentfalsethe http.Agent to use
pfx-Certificate, Private key and CA certificates to use for SSL.
key-Private key to use for SSL.
passphrase-A string of passphrase for the private key or pfx.
cert-Public x509 certificate to use.
ca-An authority certificate or array of authority certificates to check the remote host against.
ciphers-A string describing the ciphers to use or exclude. Consult the cipher format list for details on the format.
rejectUnauthorizedtrueIf true, the server certificate is verified against the list of supplied CAs. An “error” event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent.
perMessageDeflatetrueparameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable.
extraHeaders{}Headers that will be passed for each request to the server (via xhr-polling and via websockets). These values then can be used during handshake or for special proxies.
forceNodefalseUses NodeJS implementation for websockets - even if there is a native Browser-Websocket available, which is preferred by default over the NodeJS implementation. (This is useful when using hybrid platforms like nw.js or electron)
localAddress-the local IP address to connect to

manager.reconnection([value])

  • value (Boolean)
  • Returns Manager|Boolean

Sets the reconnection option, or returns it if no parameters are passed.

manager.reconnectionAttempts([value])

  • value (Number)
  • Returns Manager|Number

Sets the reconnectionAttempts option, or returns it if no parameters are passed.

manager.reconnectionDelay([value])

  • value (Number)
  • Returns Manager|Number

Sets the reconnectionDelay option, or returns it if no parameters are passed.

manager.reconnectionDelayMax([value])

  • value (Number)
  • Returns Manager|Number

Sets the reconnectionDelayMax option, or returns it if no parameters are passed.

manager.timeout([value])

  • value (Number)
  • Returns Manager|Number

Sets the timeout option, or returns it if no parameters are passed.

manager.open([callback])

  • callback (Function)
  • Returns Manager

If the manager was initiated with autoConnect to false, launch a new connection attempt.

The callback argument is optional and will be called once the attempt fails/succeeds.

manager.connect([callback])

Synonym of manager.open([callback]).

manager.socket(nsp, options)

  • nsp (String)
  • options (Object)
  • Returns Socket

Creates a new Socket for the given namespace. Only auth ({ auth: {key: "value"} }) is read from the options object. Other keys will be ignored and should be passed when instancing a new Manager(nsp, options).

Event: ‘error’

  • error (Object) error object

Fired upon a connection error.

  1. socket.io.on("error", (error) => {
  2. // ...
  3. });

Event: ‘reconnect’

  • attempt (Number) reconnection attempt number

Fired upon a successful reconnection.

  1. socket.io.on("reconnect", (attempt) => {
  2. // ...
  3. });

Event: ‘reconnect_attempt’

  • attempt (Number) reconnection attempt number

Fired upon an attempt to reconnect.

  1. socket.io.on("reconnect_attempt", (attempt) => {
  2. // ...
  3. });

Event: ‘reconnect_error’

  • error (Object) error object

Fired upon a reconnection attempt error.

  1. socket.io.on("reconnect_error", (error) => {
  2. // ...
  3. });

Event: ‘reconnect_failed’

Fired when couldn’t reconnect within reconnectionAttempts.

  1. socket.io.on("reconnect_failed", () => {
  2. // ...
  3. });

Event: ‘ping’

Fired when a ping packet is received from the server.

  1. socket.io.on("ping", () => {
  2. // ...
  3. });

Socket

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.

A Socket is basically an EventEmitter which sends events to — and receive events from — the server over the network.

  1. socket.emit("hello", { a: "b", c: [] });
  2. socket.on("hey", (...args) => {
  3. // ...
  4. });

More information can be found here.

socket.id

  • (String)

A unique identifier for the socket session. Set after the connect event is triggered, and updated after the reconnect event.

  1. const socket = io("http://localhost");
  2. console.log(socket.id); // undefined
  3. socket.on("connect", () => {
  4. console.log(socket.id); // "G5p5..."
  5. });

socket.connected

  • (Boolean)

Whether or not the socket is connected to the server.

  1. const socket = io("http://localhost");
  2. socket.on("connect", () => {
  3. console.log(socket.connected); // true
  4. });

socket.disconnected

  • (Boolean)

Whether or not the socket is disconnected from the server.

  1. const socket = io("http://localhost");
  2. socket.on("connect", () => {
  3. console.log(socket.disconnected); // false
  4. });

socket.connect()

Added in v1.0.0

  • Returns Socket

Manually connects the socket.

  1. const socket = io({
  2. autoConnect: false
  3. });
  4. // ...
  5. socket.connect();

It can also be used to manually reconnect:

  1. socket.on("disconnect", () => {
  2. socket.connect();
  3. });

socket.open()

Added in v1.0.0

Synonym of socket.connect().

socket.send([…args][, ack])

  • args
  • ack (Function)
  • Returns Socket

Sends a message event. See socket.emit(eventName[, …args][, ack]).

socket.emit(eventName[, …args][, ack])

  • eventName (String)
  • args
  • ack (Function)
  • Returns true

Emits an event to the socket identified by the string name. Any other parameters can be included. All serializable data structures are supported, including Buffer.

  1. socket.emit("hello", "world");
  2. socket.emit("with-binary", 1, "2", { 3: "4", 5: Buffer.from([6, 7, 8]) });

The ack argument is optional and will be called with the server answer.

  1. socket.emit("ferret", "tobi", (data) => {
  2. console.log(data); // data will be "woot"
  3. });
  4. // server:
  5. // io.on("connection", (socket) => {
  6. // socket.on("ferret", (name, fn) => {
  7. // fn("woot");
  8. // });
  9. // });

socket.on(eventName, callback)

  • eventName (String)
  • callback (Function)
  • Returns Socket

Register a new handler for the given event.

  1. socket.on("news", (data) => {
  2. console.log(data);
  3. });
  4. // with multiple arguments
  5. socket.on("news", (arg1, arg2, arg3, arg4) => {
  6. // ...
  7. });
  8. // with callback
  9. socket.on("news", (cb) => {
  10. cb(0);
  11. });

The socket actually inherits every method of the Emitter class, like hasListeners, once or off (to remove an event listener).

socket.onAny(callback)

  • callback (Function)

Register a new catch-all listener.

  1. socket.onAny((event, ...args) => {
  2. console.log(`got ${event}`);
  3. });

socket.prependAny(callback)

  • callback (Function)

Register a new catch-all listener. The listener is added to the beginning of the listeners array.

  1. socket.prependAny((event, ...args) => {
  2. console.log(`got ${event}`);
  3. });

socket.offAny([listener])

  • listener (Function)

Removes the previously registered listener. If no listener is provided, all catch-all listeners are removed.

  1. const myListener = () => { /* ... */ };
  2. socket.onAny(myListener);
  3. // then, later
  4. socket.offAny(myListener);
  5. socket.offAny();

socket.listenersAny()

  • Returns Function[]

Returns the list of registered catch-all listeners.

  1. const listeners = socket.listenersAny();

socket.compress(value)

  • value (Boolean)
  • Returns Socket

Sets a modifier for a subsequent event emission that the event data will only be compressed if the value is true. Defaults to true when you don’t call the method.

  1. socket.compress(false).emit("an event", { some: "data" });

socket.disconnect()

Added in v1.0.0

  • Returns Socket

Manually disconnects the socket. In that case, the socket will not try to reconnect.

Associated disconnection reason:

  • client-side: "io client disconnect"
  • server-side: "client namespace disconnect"

If this is the last active Socket instance of the Manager, the low-level connection will be closed.

socket.close()

Added in v1.0.0

Synonym of socket.disconnect().

Flag: ‘volatile’

Added in v3.0.0

Sets a modifier for the subsequent event emission indicating that the packet may be dropped if:

  • the socket is not connected
  • the low-level transport is not writable (for example, when a POST request is already running in HTTP long-polling mode)
  1. socket.volatile.emit(/* ... */); // the server may or may not receive it

Event: ‘connect’

Fired upon connection to the Namespace (including a successful reconnection).

  1. socket.on("connect", () => {
  2. // ...
  3. });
  4. // note: you should register event handlers outside of connect,
  5. // so they are not registered again on reconnection
  6. socket.on("myevent", () => {
  7. // ...
  8. });

Event: ‘disconnect’

  • reason (String)

Fired upon disconnection. The list of possible disconnection reasons:

ReasonDescription
io server disconnectThe server has forcefully disconnected the socket with socket.disconnect()
io client disconnectThe socket was manually disconnected using socket.disconnect()
ping timeoutThe server did not send a PING within the pingInterval + pingTimeout range
transport closeThe connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)
transport errorThe connection has encountered an error (example: the server was killed during a HTTP long-polling cycle)

In the first two cases (explicit disconnection), the client will not try to reconnect and you need to manually call socket.connect().

In all other cases, the client will wait for a small random delay and then try to reconnect:

  1. socket.on("disconnect", (reason) => {
  2. if (reason === "io server disconnect") {
  3. // the disconnection was initiated by the server, you need to reconnect manually
  4. socket.connect();
  5. }
  6. // else the socket will automatically try to reconnect
  7. });

Event: ‘connect_error’

  • connect_error (Object) error object

Fired when an namespace middleware error occurs.

  1. socket.on("connect_error", (error) => {
  2. // ...
  3. });