Before we dive into the thrilling world of setting up real-time communication in NodeJS using WebSockets, let us first understand what exactly is real-time communication in brief.
Real-time communication on the web allows us to get and add resources on-demand, as and when we need them. Well, over-complicated isn’t it? Let me put it this way so you can understand it better.
The above statement is only telling, that we receive resources automatically as the server begins, and transmit them to the clients.
The WebSockets API & NodeJS
So what exactly is WebSockets now? Well, simply put, it is a protocol that allows multiway communication between the user’s browser (client) and the server that is as well, long-lived.
This type of communication facilitates users to send and receive messages to and from each other at any point of time, without having to poll the server each time.
Once a Web Socket server is established, the channels are left open as a means to offer fast connections with minimal latency and overheads.
They are a way better alternative to HTTP communication on web.
With no doubt, the web socket technology has modernized and powered up web applications today.
See Also: Microservices in NodeJS
What can I do with WebSocket in Node.js?
Although there are no specific good or bad languages to set up RTC, there is still one thing about Node.js that gives it an edge above all. The V8 version of Node.js is created to serve real-time applications.
NodeJS is JavaScript-based and it’s powerful enough to handle both the frontend and backend applications.
There’s a lot you can do with web sockets but here’s what modern applications are making use of it today for!
- Real-time stock or cryptocurrency price tracker
- Chat apps
- Live location on map
- IoT device updates
- Online auction bidding
- Live video or voice call orchestration
Getting Started with NodeJS WebSockets
In this section, I will walk you through building a web socket integrated web app using the popular Express web server.
Our basic application will be sharing the current time of the server with the client through a live socket connection.
When developing with Node.js we have the option to either directly use the WebSockets package or go with an abstraction library Socket.io which comes with fallbacks for clients.
I will cover both these tools in this article.
1) Using WebSockets
This is the simplest option to go with but remember, this has lesser features than Socket.io.
Create a new app
Adding Express for our web server
Recommended Reading: ExpressJS Tutorial
Adding WebSockets and other packages
When opting for WebSockets, ws module alone would work. However, it is recommended that we install bufferutil and utf-8-validate to enhance performance.
Require Packages
Create index.js file and get started:
const { Server } = require('ws');
Set up HTTP Server
We will require an HTTP server for serving our client-side assets as well as set up a hook for the WS server to monitor for requests.
const HOME = '/home.html';
const server = express()
.use((req, res) => res.sendFile(HOME, { root: __dirname }))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
Create WebSockets Server
const wss = new Server({ server });
Handling Connections
Now, we will listen and log our connections and disconnections in the server console.
console.log('Client connected');
ws.on('close', () => console.log('Client disconnected'));
});
Broadcast Changes
Our server will now be able to broadcast messages to clients without waiting for requests.
wss.clients.forEach((client) => {
client.send(new Date().toTimeString());
});
}, 1000);
Creating WebSocket Client
Our client code will reside in the home.html, between script tags.
var ws = new WebSocket(HOST);
var el;
ws.onmessage = function (event) {
el = document.getElementById('server-time');
el.innerHTML = 'Server time: ' + event.data;
};
Start App
You can now run your app at http://localhost:80 and see if the time is being updated in real-time. Your server logs will also print ‘Client connected’.
Using Socket.io
A real-time library like Socket.io can help you us set up features like chatrooms, namespaces, and auto-reconnects. It can also help us run our app without WebSockets support.
Add packages
Set up HTTP Server
We will require an HTTP server for serving our client-side assets as well as set up a hook for the Socket.io server to monitor for requests.
const HOME = '/home.html';
const server = express()
.use((req, res) => res.sendFile(HOME, { root: __dirname }))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
Create Socket.io Server
Handling Connections
Now, we will listen and log our connections and disconnections in the server console.
console.log('Client connected');
socket.on('disconnect', () => console.log('Client disconnected'));
});
Broadcast Changes
Our server will now be able to broadcast messages to clients without waiting for requests.
Creating Socket.io Client
Our client code will reside in the home.html, between script tags.
var el;
socket.on('time', function(timeString) {
el = document.getElementById('server-time')
el.innerHTML = 'Server time: ' + timeString;
});
Start App
You can now run your app at http://localhost:80 and see if the time is being updated in real-time. Your server logs will also print ‘Client connected’.
Conclusion
WebSockets are perfect when our apps have constant communication with the server, such as trading apps or chat apps. The open sockets perform much faster than the traditional HTTP request/response model.
Further Reading: NodeJS HTTP Calls
Resources: WebSocket package, ws package