Skip to main content

Real-Time Communication with WebSockets: A Deep Dive with a Chat App Tutorial

· 6 min read
Mr.Ed
Mr.Ed
Software Engineer

Real-Time Communication with WebSockets

WebSockets have transformed real-time web communication, making it easy for web applications to transmit data instantly without frequent HTTP requests. In this blog post, we’ll cover what WebSocket is, discuss when to use it over HTTP polling, list some popular WebSocket libraries, and build a simple chat application using Socket.IO to see it in action.

What is WebSocket?

WebSocket is a protocol that enables full-duplex communication between a client (e.g., a web browser) and a server over a single, long-lived connection. Once the WebSocket connection is established, data can be sent and received simultaneously, without the overhead of HTTP requests. This capability makes WebSocket ideal for real-time applications like chat applications, live notifications, multiplayer games, and stock trading platforms.

Key Features of WebSocket

  • Persistent Connection: WebSocket establishes a long-lasting connection that remains open, reducing the need for frequent connection setups.
  • Bi-Directional Communication: Both the client and the server can send and receive data, enabling interactive and instant data exchange.
  • Low Latency: No need for repeated HTTP requests, resulting in faster communication.

When to Use WebSocket Over HTTP Polling

Consider a situation where a stock trading platform needs to provide real-time updates to clients about stock prices. In an HTTP polling setup, the client would repeatedly request the server for updates at a set interval. This creates extra load on the server and adds latency, as clients only receive updates when they make a new request.

With WebSocket, the server can push updates to the client as soon as the stock price changes. This not only reduces the server load but also minimizes the delay, allowing clients to see updates almost instantly.

Comparison of WebSocket and HTTP Polling:

FeatureHTTP PollingWebSocket
ConnectionNew request each timePersistent connection
Data FlowUni-directionalBi-directional
LatencyMediumLow
Server LoadHigh (due to requests)Moderate

Several libraries make working with WebSocket easier and more feature-rich. Here are some of the most popular ones:

  • Socket.IO: A popular library for adding real-time, event-based communication to applications. It abstracts WebSocket and includes fallbacks for older browsers. Socket.IO also provides an easy-to-use API and supports features like broadcasting and namespaces.
  • ws: A lightweight, fast, and easy-to-use WebSocket library for Node.js, primarily used for building basic WebSocket servers with minimal overhead.
  • SockJS: A WebSocket emulation library that provides WebSocket-like APIs with HTTP-based fallbacks. It's useful for applications that need robust cross-browser compatibility.
  • SignalR: A library from Microsoft, commonly used with ASP.NET applications for adding real-time functionality to web apps. SignalR is often used with .NET backends and integrates seamlessly with the Microsoft stack.
  • Phoenix Channels: An Elixir-based WebSocket library, typically used with the Phoenix Framework, to provide real-time communication with a focus on scalability and high concurrency.

Building a Chat App with WebSocket Using Node.js and Socket.IO

To see WebSocket in action, let’s create a simple real-time chat application using Node.js and Socket.IO. This library is available for both client and server-side JavaScript, making it ideal for quickly building real-time features.

Prerequisites

You’ll need:

  • Node.js and npm installed
  • A basic understanding of JavaScript

Step 1: Set Up the Project

Create a new directory for your project, navigate to it, and initialize a new Node.js project.

mkdir websocket-chat
cd websocket-chat
npm init -y

Install the required dependencies: express for the HTTP server and socket.io for WebSocket functionality.

npm install express socket.io

Step 2: Create the Server

In the root directory, create a file named server.js and add the following code to set up an Express server with Socket.IO.

server.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

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

io.on('connection', (socket) => {
console.log('A user connected');

// Listen for chat messages
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});

// Handle user disconnect
socket.on('disconnect', () => {
console.log('User disconnected');
});
});

server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});

Here’s a breakdown:

  • We create an HTTP server with Express and integrate it with Socket.IO.
  • When a client connects, we log a message and listen for chat message events. When a message is received, it’s broadcasted to all connected clients using io.emit().

Step 3: Create the Client-Side Code

Create an index.html file in the same directory. This will contain the basic HTML structure and client-side JavaScript to connect to the WebSocket server and handle chat messages.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Chat</title>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>

<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();

// Form submit handler
document.getElementById('form').addEventListener('submit', (event) => {
event.preventDefault();
const input = document.getElementById('input');
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});

// Listen for chat messages from the server
socket.on('chat message', (msg) => {
const item = document.createElement('li');
item.textContent = msg;
document.getElementById('messages').appendChild(item);
});
</script>
</body>
</html>

Explanation of Client Code:

  • The client connects to the server using io(), which is provided by the Socket.IO client library.
  • When the user submits the form, the chat message is sent to the server via socket.emit('chat message', msg).
  • The client listens for incoming chat message events and displays each message in the <ul> element.

Step 4: Run the Chat Application

Start the server with the following command:

node server.js

Open your browser and navigate to http://localhost:3000. You should see a simple chat interface. Open multiple browser tabs or windows to simulate multiple users, and type messages to see the real-time chat in action.

Conclusion

In this tutorial, we covered the basics of WebSocket, why it’s beneficial for real-time applications, some popular WebSocket libraries, and a step-by-step guide to building a chat application using Socket.IO. This example demonstrates the power of WebSocket in creating interactive, real-time experiences that modern web users expect.

For a more robust application, consider adding user authentication, private rooms, and handling message storage on the server side. Socket.IO also supports namespaces and rooms, which are useful for organizing users in larger applications.

Happy coding! 👨‍💻