Web Sockets: A Bidirectional Communication Marvel

Tahseen Rasheed
4 min readDec 21, 2023

--

Photo by Christopher Robin Ebbinghaus on Unsplash

Introduction:

Web sockets have revolutionized the way we enable real-time, bidirectional communication on the web. In this blog post, we’ll dive into the world of web sockets, exploring their significance, the underlying handshake process, use cases, and the pros and cons associated with this technology.

Understanding the Need for Web Sockets:

Traditional web communication relies on HTTP, a stateless protocol that follows a request-response model. While HTTP serves well for many scenarios, it falls short when it comes to real-time, bidirectional communication. The idea of exposing TCP, a bidirectional protocol, to the web seems tempting, but it poses security risks, and the web’s protective HTTP umbrella prevents such exposure. Enter web sockets, a solution built on top of HTTP, providing a secure means to establish bidirectional communication between clients and servers.

The Web Socket Handshake:

The magic of web sockets lies in the handshake process. A client initiates a connection by sending a special HTTP request with an “Upgrade” header. If the server understands this header and agrees to the upgrade, the connection transforms into a web socket, allowing bidirectional communication. The handshake involves a special key and a sub-protocol, adding an extra layer of security and ensuring that only knowledgeable clients can establish a web socket connection.

Use Cases of Web Sockets:

  1. Chat Applications: Web sockets are perfect for building real-time chat applications, allowing users to send and receive messages instantly.
  2. Live Feeds: Applications requiring continuous updates, such as social media feeds or news tickers, can benefit from the push capabilities of web sockets.
  3. Multiplayer Gaming: Real-time interaction is crucial in multiplayer games, and web sockets provide a low-latency solution for smooth gaming experiences.
  4. Collaborative Editing: Platforms enabling multiple users to collaborate on a document in real-time can leverage web sockets for seamless communication.

Pros and Cons of Web Sockets:

Pros:

  1. Full Duplex Communication: Web sockets enable simultaneous communication between the client and server without the need for repeated requests.
  2. Compatibility: As web sockets are built on top of HTTP, they are firewall-friendly and can work seamlessly across different environments.
  3. Push Notifications: The bidirectional nature of web sockets allows for efficient push notification systems, reducing the need for constant polling.

Cons:

  1. Stateful Nature: Web sockets maintain state on both the server and client sides, making horizontal scaling more challenging.
  2. Proxy Challenges: Configuring proxies for web sockets, especially at layer 7, can be complex, and some proxies may terminate connections if not handled correctly.
  3. Connection Management: Handling disconnected clients and maintaining a clean list of active connections requires additional logic.

Building a Simple Web Socket Chat Application:

For a hands-on experience, let’s consider a simple web socket chat application using Node.js and the “ws” library. The application establishes a web socket connection, allowing multiple users to send and receive messages in real-time. The server maintains an array of connections and broadcasts messages to all connected clients.

Step 1: Install Dependencies

Ensure you have Node.js installed on your machine. Then, create a new project folder and run the following command in your terminal to initialize a new Node.js project and install the “ws” library:

npm init -y
npm install ws

Step 2: Create the Server (server.js)

Create a file named server.js and implement the server logic:

const WebSocket = require('ws');
const http = require('http');
const express = require('express');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

const connections = [];

wss.on('connection', (ws) => {
// Add new connection to the array
connections.push(ws);

// Broadcast messages to all connected clients
ws.on('message', (message) => {
connections.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});

// Handle disconnection
ws.on('close', () => {
const index = connections.indexOf(ws);
if (index !== -1) {
connections.splice(index, 1);
}
});
});

// Serve HTML page (optional)
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});

// Start the server
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});

Step 3: Create the HTML Page (index.html)

Create an HTML file named index.html to serve as the client interface:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<div id="chat"></div>
<input type="text" id="messageInput" placeholder="Type your message">
<button onclick="sendMessage()">Send</button>

<script>
const socket = new WebSocket('ws://localhost:8080');

socket.onmessage = (event) => {
const chatDiv = document.getElementById('chat');
const message = document.createElement('p');
message.innerText = event.data;
chatDiv.appendChild(message);
};

function sendMessage() {
const messageInput = document.getElementById('messageInput');
const message = messageInput.value;

if (message.trim() !== '') {
socket.send(message);
messageInput.value = '';
}
}
</script>
</body>
</html>

Step 4: Run the Application

Run the server by executing the following command in your terminal:

node server.js

Visit http://localhost:8080 in your web browser to open the chat application. Open multiple browser tabs or devices to simulate different users. Messages sent by one user will be broadcast to all connected users in real-time.

Congratulations! You’ve just built a simple web socket chat application using Node.js and the “ws” library. Feel free to enhance and customize the application based on your requirements.

Conclusion:

Web sockets have paved the way for efficient, real-time communication on the web, opening doors to a myriad of interactive and collaborative applications. Understanding their handshake process, exploring use cases, and weighing the pros and cons empower developers to make informed decisions when implementing web sockets in their projects. Embrace the bidirectional power of web sockets to create dynamic, responsive, and engaging web applications.

--

--

No responses yet