Discovering WebSockets using some Coding
If you like the free content I put out, consider subscribing to my newsletter on substack to get a well-researched article every week delivered straight to your inbox.
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.
Peer-to-peer communication visualized using Multiplayer
How is it different than HTTP? ??
The WebSockets differ from the traditional HTTP in the following ways:
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:
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!
Curious Engineer is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.
Software Engineer 2 | Backend Engineer at Microsoft
2 个月This was great ! Let’s also discuss maybe how do we scale the server part of websocket. That’s the foundation of scalable chat applications. There are a lot of clients getting connected to websocket servers, how do we usually maintain this state?
Recruiting Coordinator | The University of Oklahoma | Women in Leadership Program | Offered in Partnership with the Zschool
2 个月Let's connect and share your CV