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>
    <script>
    const socket = io(‘http://localhost‘);
    </script>
  1. const io = require(‘socket.io-client’);
    // or with import syntax
    import io from socket.io-client’;

io.protocol

  • (Number)

The protocol revision number (currently: 4).

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)
  • 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”);

    const socket = io(“ws://example.com/my-namespace”, {
    reconnectionDelayMax: 10000,
    query: {
    auth: 123
    }
    });

is the short version of:

  1. const { Manager } = require(“socket.io-client”);

    const manager = new Manager(“ws://example.com”, {
    reconnectionDelayMax: 10000
    });

    const socket = manager.socket(“/my-namespace”, {
    query: {
    auth: 123
    }
    });

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

Initialization examples

With multiplexing

By default, a single connection is used when connecting to different namespaces (to minimize resources):

  1. const socket = io();
    const adminSocket = io(‘/admin’);
    // a single connection will be established

That behaviour can be disabled with the forceNew option:

  1. const socket = io();
    const adminSocket = io(‘/admin’, { forceNew: true });
    // will create two distinct connections

Note: reusing the same namespace will also create two connections

  1. const socket = io();
    const socket2 = io();
    // will also create two distinct connections

With custom path

  1. const socket = io(‘http://localhost‘, {
    path: ‘/myownpath
    });

    // server-side
    const io = require(‘socket.io’)({
    path: ‘/myownpath
    });

The request URLs will look like: localhost/myownpath/?EIO=3&transport=polling&sid=<id>

  1. const socket = io(‘http://localhost/admin‘, {
    path: ‘/mypath
    });

Here, the socket connects to the admin namespace, with the custom path mypath.

The request URLs will look like: localhost/mypath/?EIO=3&transport=polling&sid=<id> (the namespace is sent as part of the payload).

With query parameters

  1. const socket = io(‘http://localhost?token=abc‘);

    // server-side
    const io = require(‘socket.io’)();

    // middleware
    io.use((socket, next) => {
    let token = socket.handshake.query.token;
    if (isValid(token)) {
    return next();
    }
    return next(new Error(‘authentication error’));
    });

    // then
    io.on(‘connection’, (socket) => {
    let token = socket.handshake.query.token;
    // …
    });

With query option

  1. const socket = io({
    query: {
    token: cde
    }
    });

The query content can also be updated on reconnection:

  1. socket.on(‘reconnect_attempt’, () => {
    socket.io.opts.query = {
    token: fgh
    }
    });

With extraHeaders

This only works if polling transport is enabled (which is the default). Custom headers will not be appended when using websocket as the transport. This happens because the WebSocket handshake does not honor custom headers. (For background see the WebSocket protocol RFC)

  1. const socket = io({
    transportOptions: {
    polling: {
    extraHeaders: {
    x-clientid’: abc
    }
    }
    }
    });

    // server-side
    const io = require(‘socket.io’)();

    // middleware
    io.use((socket, next) => {
    let clientId = socket.handshake.headers[‘x-clientid’];
    if (isValid(clientId)) {
    return next();
    }
    return next(new Error(‘authentication error’));
    });

With websocket transport only

By default, a long-polling connection is established first, then upgraded to “better” transports (like WebSocket). If you like to live dangerously, this part can be skipped:

  1. const socket = io({
    transports: [‘websocket’]
    });

    // on reconnection, reset the transports option, as the Websocket
    // connection may have failed (caused by proxy, firewall, browser, …)
    socket.on(‘reconnect_attempt’, () => {
    socket.io.opts.transports = [‘polling’, websocket’];
    });

With a custom parser

The default parser promotes compatibility (support for Blob, File, binary check) at the expense of performance. A custom parser can be provided to match the needs of your application. Please see the example here.

  1. const parser = require(‘socket.io-msgpack-parser’); // or require(‘socket.io-json-parser’)
    const socket = io({
    parser: parser
    });

    // the server-side must have the same parser, to be able to communicate
    const io = require(‘socket.io’)({
    parser: parser
    });

With a self-signed certificate

  1. // server-side
    const fs = require(‘fs’);
    const server = require(‘https’).createServer({
    key: fs.readFileSync(‘server-key.pem’),
    cert: fs.readFileSync(‘server-cert.pem’)
    });
    const io = require(‘socket.io’)(server);
    server.listen(3000);

    // client-side
    const socket = io({
    // option 1
    ca: fs.readFileSync(‘server-cert.pem’),

    // option 2. WARNING: it leaves you vulnerable to MITM attacks!
    rejectUnauthorized: false
    });