Introduction
Socket.io is a popular JavaScript library that enables real-time bidirectional communication between web clients and servers. It is commonly used to add real-time capabilities to Node.js applications. In this article, we will learn how to get started with Socket for building real-time apps.
Overview
Some key features of Socket.io include:
- Real-time bidirectional communication between client and server
- Fast and reliable data transfer using WebSocket protocol
- Fallback to HTTP long-polling in older browsers
- Supports broadcasting to multiple sockets
- Automatic reconnection support
- Works on all platforms – browser, mobile, desktop etc.
Socket is built on top of the WebSocket protocol and provides additional features like broadcasting, namespacing, middleware etc. It handles the intricacies of ensuring real-time connectivity across different browsers seamlessly.
Basic Example
To use Socket.io in Node.js, first install it:
npm install socket.io
On the server:
// index.js
const io = require('socket.io')();
io.on('connection', socket => {
// socket object for each client
console.log('Client connected');
});
io.listen(3000);
This creates a Socket server instance listening on port 3000 for incoming connections.
On the client side:
<!-- index.html -->
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io(); // connect to server
socket.on('connect', () => {
console.log('Connected!');
});
</script>
The Socket client library establishes the WebSocket connection.
Handling Events
Socket uses events for real-time messaging between clients and server.
Server can listen to events from a client:
socket.on('message', msg => {
console.log(msg);
});
And emit events that clients can listen to:
socket.emit('greet', 'Hello!');
Client can emit events that the server can listen to:
socket.emit('message', 'Hi!');
And listen to events emitted by the server:
socket.on('greet', msg => {
console.log(msg); // Hello!
});
This allows real-time synchronous communication.
Namespaces
To group events into separate channels, Socket provides namespaces:
// server
const adminNamespace = io.of('/admin');
adminNamespace.on('connection', socket => {
// admin related events
});
const userNamespace = io.of('/user');
userNamespace.on('connection', socket => {
// user related events
});
Namespaces help structure events from different modules separately.
Broadcasting Events
Socket allows broadcasting events to all connected sockets or selective groups:
io.emit('message', 'Hello to all'); // all clients
adminNamespace.emit('message', 'Hi admins'); // all in admin namespace
socket.broadcast.emit('msg', 'Hello others'); // all except this client
This makes it easy to push real-time notifications to relevant users.
Disconnection Handling
Socket.io tracks disconnections automatically and fires a disconnect
event:
socket.on('disconnect', () => {
console.log('Socket disconnected');
});
This also works when namespaces are used. Disconnection handling enables real-time tracking of connected clients.
Comparison between Socket.io vs WebSocket
Factor | Socket.io | WebSockets |
---|---|---|
Communication | Bidirectional | Bidirectional |
Auto reconnect | Yes | No |
Fallback options | Polling, etc | None |
Browser support | All browsers | Most browsers |
Events and namespaces | Supports | No native support |
Middleware | Pluggable | None |
Client libraries | JS, C++, Swift | JS primarily |
Use cases | Real-time apps, Chat, Notifications | Games, Apps needing raw speed |
Socket provides WebSocket comparable bi-directional communication while also handling tricky reconnects, fallbacks and namespace multiplexing across browsers seamlessly.
Frequently Asked Questions
- Does Socket.io work with plain WebSockets?
Socket uses WebSocket as the primary transport. But it provides fallback options and other benefits on top of raw WebSockets.
- When should Socket.io vs WebSockets be used?
Socket is suitable for most real-time apps. Raw WebSockets make sense for cases where performance is critical like games or financial apps.
- Can Socket.io connect to non-Node.js servers?
Yes, Socket clients can connect to other server technologies like Python, Ruby, Java etc. The server just needs to use a compatible Socket library.
- Does Socket.io require Node.js on the client?
No, Socket provides client libraries for web browsers, iOS, Android, C++, etc. Real-time apps can be built without Node.js on client.
- What are the limitations of Socket.io?
There is a slight overhead compared to raw WebSockets. Beyond a certain scale, custom WebSockets server and client handling code may be needed.
Conclusion
Socket is the standard way of enabling real-time capabilities in Node.js applications. Its robust WebSocket based transport mechanisms combined with events, namespaces and broadcasting makes it indispensable for modern real-time apps. Socket smooths over cross-browser inconsistencies in WebSockets and provides the flexibility needed for most use cases.