Security News
vlt Debuts New JavaScript Package Manager and Serverless Registry at NodeConf EU
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
socket.io
Advanced tools
The socket.io npm package enables real-time, bidirectional and event-based communication between web clients and servers. It is primarily used to build real-time web applications and has features like broadcasting to multiple sockets, storing data associated with each client, and asynchronous I/O.
Real-time bidirectional event-based communication
This feature allows the server to establish a WebSocket connection with the client for real-time communication. The server listens for events like 'connection', 'chat message', and 'disconnect' to react accordingly.
const io = require('socket.io')(3000);
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
Broadcasting
Broadcasting allows a server to send a message to all connected clients except for the one that triggered the message. This is useful for notifying all users about the actions of one.
io.on('connection', (socket) => {
socket.broadcast.emit('user connected', 'A new user has joined the chat');
});
Namespaces and Rooms
Socket.IO allows for the creation of Namespaces and Rooms which can be used to divide the clients into different groups for targeted broadcasting and communication.
const chat = io.of('/chat').on('connection', (socket) => {
socket.join('some room');
chat.to('some room').emit('some event');
});
The 'ws' package is a simple WebSocket library for Node.js. Unlike socket.io, it does not provide high-level features like broadcasting to multiple sockets or automatic reconnection.
Engine.io is the low-level engine that powers socket.io. It provides the bare WebSocket-like API and is responsible for handling the transport logistics. It is less feature-rich compared to socket.io.
SockJS is a JavaScript library that provides a WebSocket-like object. It is similar to socket.io in that it offers a fallback mechanism for environments where WebSockets are not supported.
Faye is a set of tools for simple publish-subscribe messaging between web clients. It's more focused on the pub/sub paradigm and lacks some of the real-time communication features that socket.io offers.
Socket.IO enables real-time bidirectional event-based communication. It consists of:
Some implementations in other languages are also available:
Its main features are:
Connections are established even in the presence of:
For this purpose, it relies on Engine.IO, which first establishes a long-polling connection, then tries to upgrade to better transports that are "tested" on the side, like WebSocket. Please see the Goals section for more information.
Unless instructed otherwise a disconnected client will try to reconnect forever, until the server is available again. Please see the available reconnection options here.
A heartbeat mechanism is implemented at the Engine.IO level, allowing both the server and the client to know when the other one is not responding anymore.
That functionality is achieved with timers set on both the server and the client, with timeout values (the pingInterval
and pingTimeout
parameters) shared during the connection handshake. Those timers require any subsequent client calls to be directed to the same server, hence the sticky-session
requirement when using multiples nodes.
Any serializable data structures can be emitted, including:
Sample code:
io.on('connection', socket => {
socket.emit('request', /* … */); // emit an event to the socket
io.emit('broadcast', /* … */); // emit an event to all connected sockets
socket.on('reply', () => { /* … */ }); // listen to the event
});
Browser support is tested in Sauce Labs:
In order to create separation of concerns within your application (for example per module, or based on permissions), Socket.IO allows you to create several Namespaces
, which will act as separate communication channels but will share the same underlying connection.
Within each Namespace
, you can define arbitrary channels, called Rooms
, that sockets can join and leave. You can then broadcast to any given room, reaching every socket that has joined it.
This is a useful feature to send notifications to a group of users, or to a given user connected on several devices for example.
Note: Socket.IO is not a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the ack id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server (like ws://echo.websocket.org
) either. Please see the protocol specification here.
npm install socket.io
The following example attaches socket.io to a plain Node.JS
HTTP server listening on port 3000
.
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('event', data => { /* … */ });
client.on('disconnect', () => { /* … */ });
});
server.listen(3000);
const io = require('socket.io')();
io.on('connection', client => { ... });
io.listen(3000);
Starting with 3.0, express applications have become request handler
functions that you pass to http
or http
Server
instances. You need
to pass the Server
to socket.io
, and not the express application
function. Also make sure to call .listen
on the server
, not the app
.
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);
Like Express.JS, Koa works by exposing an application as a request
handler function, but only by calling the callback
method.
const app = require('koa')();
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);
To integrate Socket.io in your Fastify application you just need to
register fastify-socket.io
plugin. It will create a decorator
called io
.
const app = require('fastify')();
app.register(require('fastify-socket.io'));
app.io.on('connection', () => { /* … */ });
app.listen(3000);
Please see the documentation here.
The source code of the website can be found here. Contributions are welcome!
Socket.IO is powered by debug.
In order to see all the debug output, run your app with the environment variable
DEBUG
including the desired scope.
To see the output from all of Socket.IO's debugging scopes you can use:
DEBUG=socket.io* node myapp
npm test
This runs the gulp
task test
. By default the test will be run with the source code in lib
directory.
Set the environmental variable TEST_VERSION
to compat
to test the transpiled es5-compat version of the code.
The gulp
task test
will always transpile the source code into es5 and export to dist
first before running the test.
Support us with a monthly donation and help us continue our activities. [Become a backer]
Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]
FAQs
node.js realtime framework server
The npm package socket.io receives a total of 4,843,107 weekly downloads. As such, socket.io popularity was classified as popular.
We found that socket.io demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
Security News
Research
The Socket Research Team uncovered a malicious Python package typosquatting the popular 'fabric' SSH library, silently exfiltrating AWS credentials from unsuspecting developers.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.