HTTP requests follow a one-way request-response cycle: the client asks for data, and the server responds. If the server has new data (like a new message in a chat room), it cannot push it to the client.
To build real-time collaborative applications, we must use WebSockets, which open a persistent, two-way connection between the client and server.
Advertisement
Nextsem Academy
Lesson: p6-4-chat
Slide 1 / 5
P6.4: Realtime Chat Client
HTTP requests follow a one-way request-response cycle: the client asks for data, and the server responds. If the server has new data (like a new message in a chat room), it cannot push it to the client.
To build real-time collaborative applications, we must use WebSockets, which open a persistent, two-way connection between the client and server.
Slide 2 / 5
1. WebSockets vs HTTP
HTTP Requests: Client pulls data. Connection closes after response. Great for static pages, blog articles, and catalog lists.
WebSocket Tunnels: Bidirectional persistence. Server pushes data instantly. Essential for messaging, live collaborative documents, and multiplayer games.
Example
HTTP (Pull):
Client โโโ(Request)โโโโบ Server โโโ(Response)โโโโบ [Connection Closed]
WebSockets (Push):
Client โโโโ(Persistent Bidirectional Tunnel)โโโโบ Server
Interactive Code
Slide 3 / 5
2. Setting Up Socket.io Backend
Socket.io is a popular library that simplifies WebSocket implementations, providing fallback protocols for older browsers and room management.
Step 1: Install Socket.io
>_Command Prompt
โโโ
npm install socket.io
Interactive Console
Step 2: Configure Express Server with Socket.io
Example
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, {
cors: { origin: "*" }
});
// Listen for connection events
io.on('connection', (socket) => {
console.log(`User connected: ${socket.id}`);
// Listen for message broadcasts
socket.on('send_message', (data) => {
// Broadcast message to all other connected clients
socket.broadcast.emit('receive_message', data);
});
socket.on('disconnect', () => {
console.log(`User disconnected: ${socket.id}`);
});
});
server.listen(5000, () => console.log('Socket server running on port 5000'));
Interactive Code
Slide 4 / 5
3. Connecting the React Frontend
To query your real-time socket server, install the client library in your React application: