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: [] });

    socket.on("hey", (...args) => {
    // ...
    });

More information can be found here.

socket.id

  • (String)

An 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");

    console.log(socket.id); // undefined

    socket.on("connect", () => {
    console.log(socket.id); // "G5p5..."
    });

socket.connected

  • (Boolean)

Whether or not the socket is connected to the server.

  1. const socket = io("http://localhost");

    socket.on("connect", () => {
    console.log(socket.connected); // true
    });

socket.disconnected

  • (Boolean)

Whether or not the socket is disconnected from the server.

  1. const socket = io("http://localhost");

    socket.on("connect", () => {
    console.log(socket.disconnected); // false
    });

socket.connect()

Added in v1.0.0

  • Returns Socket

Manually connects the socket.

  1. const socket = io({
    autoConnect: false
    });

    // ...
    socket.connect();

It can also be used to manually reconnect:

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

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 datastructures are supported, including Buffer.

  1. socket.emit("hello", "world");
    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) => {
    console.log(data); // data will be "woot"
    });

    // server:
    // io.on("connection", (socket) => {
    // socket.on("ferret", (name, fn) => {
    // fn("woot");
    // });
    // });

socket.on(eventName, callback)

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

Register a new handler for the given event.

  1. socket.on("news", (data) => {
    console.log(data);
    });

    // with multiple arguments
    socket.on("news", (arg1, arg2, arg3, arg4) => {
    // ...
    });
    // with callback
    socket.on("news", (cb) => {
    cb(0);
    });

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) => {
    console.log(`got ${event}`);
    });

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) => {
    console.log(`got ${event}`);
    });

socket.offAny([listener])

  • listener (Function)

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

  1. const myListener = () => { /* ... */ };

    socket.onAny(myListener);

    // then, later
    socket.offAny(myListener);

    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", () => {
    // ...
    });

    // note: you should register event handlers outside of connect,
    // so they are not registered again on reconnection
    socket.on("myevent", () => {
    // ...
    });

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) => {
    if (reason === "io server disconnect") {
    // the disconnection was initiated by the server, you need to reconnect manually
    socket.connect();
    }
    // else the socket will automatically try to reconnect
    });

Event: ‘connect_error’

  • connect_error (Object) error object

Fired when an namespace middleware error occurs.

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

Caught a mistake? Edit this page on GitHub