DEV Community

Rithika R
Rithika R

Posted on

Web-Sockets Concept & Real-time Chat Application Working Principles using Web-Sockets

Before getting into the story, I will ask the question about what web token is and why we actually use this protocol and where and how it actually differs from the http/https protocol. So, for the above question, I will answer through this article.

Okay Let's dive in,

Web-Sockets

Web-Sockets are a powerful tool for real-time, bidirectional communication between a client and a server. Unlike HTTP requests, client initiates every interaction, web-Sockets allow the server to push data to the client whenever necessary. Web-Socket is mostly suitable for real-time updates like chat applications and live notifications.
Here we have some questions about the difference between HTTP/HTTP and web-sockets and why Web-Sockets are helpful in chat application.

Difference between Http/Https and Web-Sockets

HTTP/HTTPS

  • Request-Response Model: HTTP is a request-response protocol, where the client sends a request to the server, and the server responds with the requested data.

  • Stateless: Each HTTP request is independent and does not retain any information from previous requests.

  • Unidirectional: The client initiates a request, and the server responds with data. The server cannot initiate a request to the client.

WebSockets

  • Bi-directional Communication: WebSockets establish a persistent, bi-directional communication channel between the client and server, allowing both parties to send data at any time.

  • Stateful: A WebSocket connection retains the state of the conversation between the client and server.

  • Event-driven: WebSockets are designed to handle events, such as user interactions, network changes, or server-side updates.

  • WS (WebSocket Protocol): WebSockets use the WS protocol, which is an extension of the HTTP protocol.

  • Real-time: WebSockets are designed for real-time communication, enabling fast and efficient data transfer.

How WebSockets Actually work

  1. Establishing a connection: The client initaites a WebSocket connection by sending a request to the server. This request is similar to the http request but includes an upgrade header to switch the protocol from http to WebSocket. The Server responds with a 101 Switching Protocols status code, indicating that the connection has been upgraded.

  2. Maintaining the Connection: Once the connection is established, it remains open, allowing both the client and server to send messages to each other at any time.

3.Filtering for Removing Disconnected Sockets: When the Socket is closed, the Server uses the filter method to remove the disconnected socket from the sockets array or similar data structure.

Here are some sample basic codes of Web-sockets establishment,

Server

const WebSocket = require('ws');
const server = new WebSocket.Server({
port: 8080 });
let sockets = 0;
server.on('connection', function(socket) {
sockets.push(socket);
// When you receive a message, send that message to every socket.
socket.on('message', function(msg) {
sockets.forEach(s => s.send(msg));
});
// When a socket closes, or disconnects, remove it from the array.
socket.on('close', function() {
sockets = sockets.filter(s => s !== socket); });
});

Client

const socket = new WebSocket('ws://localhost:8080');
// When the connection is established 
socket.onopen = function(event) { 
 console.log('Connected to the WebSocket server'); 
};
// When a message is received from the server 
socket.onmessage = function(event) { 
 console.log('Received message: ' + event.data); 
};
// When an error occurs 
socket.onerror = function(event) { 
 console.log('Error occurred'); 
};
// When the connection is closed 
socket.onclose = function(event) { 
 console.log('Connection closed'); 
};
// Send a message to the server 
function sendMessage(message) { 
 socket.send(message); 
}
// Example usage 
sendMessage('Hello, server!');

The above section are the basics of Web-Sockets, let's talk about Web-Sockets with real life examples,

Chat Application

Do know how we are all getting a reply or sending the message as soon as possible. If we follow HTTP or other protocols which will initiate a request/response model for every msg which cause more trouble or cause time delay. By avoiding these consequences, using WebSocket, which will create a socket for the person, the person get/send the message until the socket closes (until you are online or else until the time setup).

Let's talk about science - based that's makes you more understandable,

Scenario: Person1 sends a message to Person2 and Person3

1.Establishing the Connections: when the Person1, Person2, Person3 connect to the WebSocket Server, each of them establishes an individual WebSocket connection. The server maintains a list of these connections(sockets).

How a person gets an individual Web-Socket :

  • User Authentication: When the user connects to the WebSocket Server, they should authenticate themselves. This can be done using a login system where provide their credentials (e.g email id, password). Once authenticated, the Server assigns a unique user ID (generate using the UUID or other method) to each user.

  • Storing User Information: The Server maintains a mapping of user IDs to WebSocket connections. This allows the server to identify which Socket belongs to which user.

  • Sending Message: When the user sends a message, they specify the recipient's user ID. The server uses the mapping to find the recipient's socket and sends the message to that socket.

  1. Storing Connections: The Server keeps track of each connection in an array or similar data structure.
  2. Sending Messages: When Person1 sends a message, the server receives it and can decide how to handle it. In a simple broadcast scenario, the server sends the message to all connected clients.
  3. Person-to-Person communication: The Server needs to know which socket corresponds to which person. This can be achieved by associating each Socket with a unique identifier. When Person1 sends message to Person2, the server identifies Person2's socket and sends the message only to that socket.

Server

const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
let sockets = [];
server.on('connection', function(socket) {
// Assign a unique ID to each socket (e.g., user ID)
socket.userId = generateUniqueId();
sockets.push(socket);
socket.on('message', function(msg) {
Let message = JSON.parse(msg);
let targetSocket = sockets.find(s s.userId message.targetUser
if (targetSocket) {
targetSocket.send(message.content);
}
});
socket.on('close', function() {
sockets = sockets.filter(s => s !== socket);
});
});
function generateUniqueId() {
return Math.random().toString(36).substr(2, 9);
}

Client

let message = {
targetUserId: 'person2Id', content: 'Hello, Person2!'
};
socket.send(JSON.stringify(message));

The above article provides an overview of Web-Socket. If anyone needs a deeper understanding of authentication or API protocols, please comment, and I will do my best to address it in a future article. Additionally, I will write an article covering real-time applications that enhance its effectiveness. Thank you

Top comments (0)