Discovering WebSockets with some Coding
This article attempts to explore what's the fuss about Websockets
In this blog, I intend to find answers to these questions.
What is a WebSocket? How does it differ from traditional HTTP connections that I’ve been building in day to day life? Is there any code that can explain how WebSockets work? What are some popular use cases of WebSocket present around us?
A big shout out to the sponsor for this edition who help to run this newsletter for free 🎉
Multiplayer auto-documents your system, from the high-level logical architecture down to the individual components, APIs, dependencies, and environments. Perfect for teams who want to speed up their work flows and consolidate their technical assets.
What is a WebSocket?
WebSocket is a full-duplex communication protocol that provides a persistent connection between a client and a server. Full-duplex communication is a type of data transmission where information can flow in both directions simultaneously. This means that a sender and receiver can send and receive data at the same time without having to wait for the other party to finish transmitting.
Please note that the full duplex communication is between the server and the client so that the client can send a message to the server and then the server sends it to the right receiver. Also, the server should be able to send a message to the client received from other clients.
For example: you can message your friend on WhatsApp and they can WhatsApp you as well at the same time. Similarly, you can do video conferencing with another person and data packets flow in both directions.
In the below image, you can see that clients are connected to the server and they are sending messages via server to the other client. The server’s responsibility is to manage various clients connected to it and make sure the message from the sender goes to the only receiver it is intended for.
How is it different than HTTP? 🤯
The WebSockets differ from the traditional HTTP in the following ways:
One-way vs Two-way communication: In the HTTP connection, only the client can request to the server whereas in the WebSockets, both client and server can send data to each other.
Connection persistence: Once HTTP connections are established, they remain open for a long time but still can be closed due to idle timeout or server-side/client-side configurations. However, the Websockets are designed to remain open indefinitely so that near real-time communication can happen between the client and the server.
UseCases: HTTP is primarily used for request-response interactions like file downloads from a server, form submission, and getting static/dynamic content(images/videos) from a server, etc. On the other hand, WebSockets are designed for Live Updates, real-time gaming, and chat applications(like WhatsApp, Telegram), live video streaming, etc.
Do WebSockets internally implement HTTP Protocol?
Quoting this answer from a StackOverflow question:
“Yes, initially, then they switch to the webSocket protocol. All WebSocket connections start with an HTTP request with a header that requests an upgrade to the WebSocket protocol. If the receiving server agrees, then the two sides switch protocols from HTTP to WebSocket, and from then on the connection uses the WebSocket protocol.
So, ALL WebSocket servers MUST support that initial HTTP request because that's how all WebSocket connections are started.”
Let’s do some Coding!
Since I have no expertise in writing WebSockets, I took some help from ChatGPT to build a simple chat application and understand the underlying semantics. Here are the following steps to build a simple chat app.
I highly recommend you do the following steps on your local to get a feel of the WebSocket connections. I have used Node.js as an example here because it provides a library called “ws” which refers to the WebSocket library used to implement WebSocket-based communication between the server and the clients. It is quite popular.
Step 1:
Install Node.js if you haven't already: Node.js Download.
Step 2:
Initialize a project using the following commands
mkdir terminal-chat-app
cd terminal-chat-app
npm init -y
Step 3:
Install the ws
package:
npm install ws
Step 4:
Create a file called server.js
that will manage connections and message broadcasting.
// server.js
const WebSocket = require('ws');
// Create a WebSocket server
const wss = new WebSocket.Server({ port: 8080 });
// Store connected clients
let clients = [];
// Broadcast message to all connected clients
function broadcast(data, sender) {
clients.forEach((client) => {
if (client !== sender && client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
}
wss.on('connection', (ws) => {
clients.push(ws);
console.log('New client connected');
// Handle incoming messages
ws.on('message', (message) => {
console.log(`Received: ${message}`);
broadcast(message, ws); // Broadcast to other clients
});
// Handle client disconnection
ws.on('close', () => {
console.log('Client disconnected');
clients = clients.filter(client => client !== ws); // Remove from client list
});
// Handle errors
ws.on('error', (err) => {
console.error('Error: ', err);
});
});
console.log('WebSocket server is running on ws://localhost:8080');
Step 5:
Now, create a simple client file client.js
that will connect to the WebSocket server.
// client.js
const WebSocket = require('ws');
const readline = require('readline');
// Connect to the WebSocket server
const ws = new WebSocket('ws://localhost:8080');
// Handle incoming messages
ws.on('message', (message) => {
console.log(`\nMessage from server: ${message}`);
});
// Handle connection open event
ws.on('open', () => {
console.log('Connected to server. Type a message:');
// Setup user input interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Send messages typed by the user
rl.on('line', (input) => {
ws.send(input);
});
});
// Handle connection close
ws.on('close', () => {
console.log('Disconnected from server');
});
// Handle errors
ws.on('error', (err) => {
console.error('Error: ', err);
});
Step 6:
Run the WebSocket Server using the command:
node server.js
Step 7:
Open multiple terminal windows or tabs to simulate different clients and run the client.js in each:
node client.js
Step 8:
Type a message in any client terminal window, you will see the message getting broadcasted from one client to all the other clients.
What is happening behind the scenes:
The
server.js
listens for WebSocket connections onws://localhost:8080
.Each
client.js
connects to this server.Any message a client sends is broadcast to all other connected clients.
You can type messages into the terminal, and they will appear in other client terminals in real-time.
Also, the code is very intuitive. In the context of WebSockets (
ws
), the termsmessage
,open
, andclose
refer to WebSocket events that occur during the lifecycle of a WebSocket connection. Each of these events triggers a corresponding event listener in your WebSocket client or server code.
We built a basic chat application but actually, it’s more of a group chat application. You can extend this application to build a peer-to-peer chat application. For that, you would have to register your clients, assign them a unique identifier, and then only broadcast the message to the destination client for whom it was meant to be. Please note that when the client sends the message, you would have to ask them which Client ID they want to send the message.
That’s it, folks for this edition of the newsletter. Hope you liked this short edition.
Please consider liking 👍 and sharing with your friends as it motivates me to bring you good content for free. If you think I am doing a decent job, share this article in a nice summary with your network. Connect with me on Linkedin or Twitter for more technical posts in the future!
Nice article Vivek, I feel using libraries abstracts out the real learning about how things are working internally but overall a good article.
I would also like you to add the drawbacks of using websockets as in persisting a connection comes with an additional cost etc.
learnt something new today! great article