Once you have installed the Socket.IO server library, you can now init the server. The complete list of options can be found here.

Standalone

const options = { /* ... */ };
const io = require('socket.io')(options);

io.on('connection', socket => { /* ... */ });

io.listen(3000);

You can also pass the port as the first argument:

const options = { /* ... */ };
const io = require('socket.io')(3000, options);

io.on('connection', socket => { /* ... */ });

This implicitly starts a Node.js HTTP server, which can be accessed through io.httpServer.

Attached to an existing HTTP server

const server = require('http').createServer();
const options = { /* ... */ };
const io = require('socket.io')(server, options);

io.on('connection', socket => { /* ... */ });

server.listen(3000);

With HTTPS:

const fs = require('fs');
const server = require('https').createServer({
key: fs.readFileSync('/tmp/key.pem'),
cert: fs.readFileSync('/tmp/cert.pem')
});
const options = { /* ... */ };
const io = require('socket.io')(server, options);

io.on('connection', socket => { /* ... */ });

server.listen(3000);

With Express

const app = require('express')();
const server = require('http').createServer(app);
const options = { /* ... */ };
const io = require('socket.io')(server, options);

io.on('connection', socket => { /* ... */ });

server.listen(3000);

More information here.

With Koa

const app = require('koa')();
const server = require('http').createServer(app.callback());
const options = { /* ... */ };
const io = require('socket.io')(server, options);

io.on('connection', socket => { /* ... */ });

server.listen(3000);

More information here.

Notable options

The complete list of options can be found here. Here are those which you will most likely use:

perMessageDeflate option

Default value: true

The WebSocket server provided by the ws package supports the permessage-deflate extension, which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each WebSocket message.

As of Socket.IO v2, it is enabled by default, though it adds a significant overhead in terms of performance and memory consumption (and the ws maintainers suggest to only enable it if it is really needed).

So you can disable it with:

const io = require('socket.io')({
perMessageDeflate: false
});

Please note that it will be disabled by default in Socket.IO v3.

maxHttpBufferSize option

Default value: 10e7

This defines how many bytes a message can be, before closing the socket. It defaults to 10e7 (100MB). You may increase or decrement this value depending on your needs.

const io = require('socket.io')({
maxHttpBufferSize: 1e5
});

It matches the maxPayload option of the ws package.

Caught a mistake? Edit this page on GitHub