Building a Real-Time Web Application with WebSockets and Node.js
By Udit Agarwal
WebSockets are a powerful technology that enables real-time communication between a web client and a server. This article explains building a real-time web app with WebSockets and Node.js.
Setting up a Node.js server
The first step in building a real-time web application with WebSockets is to set up a Node.js server. The server manages WebSocket connections and exchanges data with clients. To set up a Node.js server, install the “ws” library via npm for WebSocket server and client implementation. Once the library is installed, we can create a new server using the following code:
const WebSocket = require(‘ws’);
const wss = new WebSocket.Server({ port: 8080 });
wss.on(‘connection’, function connection(ws) {
console.log(‘Client connected’);
ws.on(‘message’, function incoming(message) {
console.log(‘Received message:’, message);
});
ws.send(‘Hello, client!’);
});
In the above code, we create a new WebSocket server on port 8080. We also set up an event listener for the “connection” event, which is triggered whenever a new client connects to the server. Inside the event listener, we log a message to the console to indicate that a new client has connected. We also set up an event listener for the “message” event, which is triggered whenever the server receives a message from a client. Inside the “message” event listener, we log the message to the console and send a response back to the client.
Setting up a web client
Next, set up a web client to connect to the WebSocket server. We can use JavaScript to create a WebSocket object and connect to the server using its URL. Once the connection is established, we can send messages to the server and receive messages from the server. Here’s an example of how to set up a web client:
const ws = new WebSocket(‘ws://localhost:8080’);
ws.onopen = function() {
console.log(‘Connected to server’);
ws.send(‘Hello, server!’);
};
ws.onmessage = function(event) {
console.log(‘Received message:’, event.data);
};
In the above code, we create a new WebSocket object and connect it to the server on port 8080. We set up an event listener for the “open” event, which is triggered when the connection to the server is established. Inside the event listener, we log a message to the console to indicate that the client has connected, and we send a message to the server. We also set up an event listener for the “message” event, which is triggered whenever a message is received from the server. We log the message to the console when the “message” event occurs.
Also Read: An Overview of Containerization and Docker
Broadcasting messages
Once we have set up the WebSocket server and web client, we can implement real-time communication between them. One way to achieve this is to broadcast messages from the server to all connected clients. To do this, we can maintain an array of connected clients and loop through the array to send messages to each client. Here’s an example:
const WebSocket = require(‘ws’);
const wss = new WebSocket.Server({ port: 8080 });
const clients = [];
wss.on(‘connection’, function connection(ws) {
console.log(‘Client connected’);
clients.push(ws);
ws.on(‘message’, function incoming(message) {
console.log(‘Received message:’, message);
// Broadcast message to all clients
clients.forEach(function(client) {
if (client !== ws) {
client.send(message);
}
});
});
ws
Bottom Line
In conclusion, using WebSockets and Node.js to build a real-time web app enables effective client-server communication. We can establish a two-way communication channel between a Node.js server and a web client by implementing WebSockets with the “ws” library. This allows the creation of real-time apps like chat rooms, online games, and collaborative editing tools.
To build a real-time web application using WebSockets and Node.js, we need to set up a Node.js server, create a web client, and implement the broadcasting of messages from the server to all connected clients. We also need to handle errors and close connections properly to ensure the stability and reliability of the application.