0% found this document useful (0 votes)
12 views9 pages

Real-Time Chat App with Express & Socket.IO

Uploaded by

alpha.indica004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views9 pages

Real-Time Chat App with Express & Socket.IO

Uploaded by

alpha.indica004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CO308N Software Lab – II

PRACTICAL : 10

Aim :
Develop a real time chat application using express js and [Link].

SOFTWARE &TOOLS REQIRED :


• Operating System: Windows / Linux / macOS
• [Link] (v14+ recommended) with npm
• [Link]
• [Link] (server and client)
• Optional: MongoDB (or any database) for message persistence
• Postman / Browser for testing
• Text Editor (Visual Studio Code recommended)
• Git (for version control)

THEORY :
1. Introduction to Real-time Web
Traditional web apps operate on a request–response model: the client asks, the server replies.
Real-time applications require two-way, low-latency communication so that servers can push
updates to clients immediately (chat, multiplayer games, collaborative editors).

2. WebSockets and [Link]

WebSocket is a standardized protocol that provides full-duplex communication channels over


a single TCP connection. [Link] is a library that sits on top of WebSockets and other
transports to provide a robust, fall-back-capable real-time layer. It adds features like
automatic reconnection, rooms/namespaces, event-based messaging, and binary support.

3. Why Express + [Link]?


Express provides a minimal, flexible HTTP server and routing; [Link] integrates
easily with an Express server to handle real-time channels while still serving static files
and REST endpoints for configuration and non-realtime operations.
CO308N Software Lab – II

4. High-level Architecture
• Client (browser or mobile) connects to Express server over HTTP to fetch the UI.
• Client then opens a [Link] connection (WebSocket or fallback) to the same server.
• Server propagates messages to all connected clients (broadcast) or to specific
rooms/users.
• Optionally, messages are persisted in a database for history.

FUNCTIONAL REQUIREMENTS :
▪ User can enter a display name and join the chat.
▪ Messages sent are broadcast to all users in the same chat room.
▪ Server timestamps messages and optionally stores them.
▪ Users can see when other users join/leave.
▪ Basic UI to show message list, input box, and online users list.
▪ Optional: private messages, typing indicators, message history load.

NON-FUNCTIONAL REQUIREMENTS :
▪ Low latency (< 200 ms typical round-trip on LAN/internet depending on network)
▪ Scalability considerations ([Link] supports clusters with adapters like Redis)
▪ Graceful reconnection and error handling
▪ Minimal security (input sanitization, rate limiting)

 REQUEST/ENDPOINT DESIGN (for the combined Express + [Link] app)

Although the chat uses WebSocket events for live messaging, Express routes are useful for
serving the UI and for management APIs.

• GET / -> Serves [Link] (chat UI)

• GET /history?limit=50 -> Optional REST endpoint to fetch the last N messages
(JSON)

• POST /config -> Optional: set room settings or moderation via REST
CO308N Software Lab – II

[Link] events (examples):

Client -> Server

• connect (built-in)

• join_room { room, name }

• leave_room { room }

• chat_message { room, text }

• typing { room }

Server -> Client

• message { id, room, name, text, ts }

• user_joined { room, name }

• user_left { room, name }

• typing { room, name }


CO308N Software Lab – II

PROGRAM :
[Link]
<!DOCTYPE html>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Simple Chat — Practical</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<style>
body{font-family:Arial;margin:0;height:100vh;display:flex;align-items:center;justify-
content:center;background:#f0f0f0}
.card{width:90%;max-width:600px;background:#fff;padding:12px;border-radius:8px;box-
shadow:0 2px 8px rgba(0,0,0,.1)}
#messages{height:300px;overflow:auto;border:1px solid #ddd;padding:8px;margin-
bottom:8px;border-radius:6px;background:#fafafa}
.msg{padding:6px;border-radius:4px;margin-bottom:6px;background:#e9f5ff}
form{display:flex;gap:8px}
input[type="text"]{flex:1;padding:8px;border:1px solid #ccc;border-radius:6px}
button{padding:8px 12px;border-
radius:6px;border:0;background:#2b7be4;color:#fff;cursor:pointer}
[Link]{color:#666;margin-left:8px;font-size:11px}
</style>
</head>
<body>
<div class="card">
<h3>Real Time Chat Application</h3>
<div id="messages"></div>

<form id="form">
<input id="input" autocomplete="off" placeholder="Type message..." />
<button>Send</button>
</form>
CO308N Software Lab – II

<p style="font-size:12px;color:#666;margin-top:8px">Open multiple browser tabs to


test.</p>
</div>

<script src="/[Link]/[Link]"></script>
<script>
const socket = io();

const form = [Link]('form');


const input = [Link]('input');
const messages = [Link]('messages');

// append message to messages div


function addMessage(data) {
const d = new Date([Link]);
const time = [Link]();
const el = [Link]('div');
[Link] = 'msg';
[Link] = `<strong>${shortId([Link])}</strong>: ${escapeHtml([Link])}
<small class="time">${time}</small>`;
[Link](el);
[Link] = [Link];
}

// send message to server


[Link]('submit', e => {
[Link]();
const txt = [Link]();
if (!txt) return;
[Link]('chat message', txt);
[Link] = '';
});
CO308N Software Lab – II

// receive messages
[Link]('chat message', data => addMessage(data));

// helper functions
function shortId(id) {
return id ? [Link](0,6) : 'anon';
}
function escapeHtml(str) {
return String(str).replace(/[&<>"']/g, m =>
({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]);
}
</script>
</body>
</html>

[Link]
// [Link] — very small Express + [Link] chat server
const express = require('express');
const http = require('http');
const { Server } = require('[Link]');
const path = require('path');

const app = express();


const server = [Link](app);
const io = new Server(server);

// Serve static client from /public


[Link]([Link]([Link](__dirname, 'public')));

// When a client connects


[Link]('connection', socket => {
CO308N Software Lab – II

[Link]('Connected:', [Link]);

// handle incoming chat message


[Link]('chat message', msg => {
// broadcast message to everyone (including sender)
[Link]('chat message', { id: [Link], text: msg, time: [Link]() });
});

// disconnect
[Link]('disconnect', () => {
[Link]('Disconnected:', [Link]);
});
});

const PORT = [Link] || 3000;


[Link](PORT, () => {
[Link](`Server running at [Link]
});

OUTPUT :
CO308N Software Lab – II

User 1 Chat :

User 2 Chat :
CO308N Software Lab – II

Real-Life Application :
• Learning Foundation: Serves as a base for understanding how web servers function.
• Web Hosting: Used to deliver simple web pages without frameworks.
• IoT Systems: Devices can communicate through lightweight HTTP servers.
• Microservices: Can be used as lightweight backend services.
• API Development: Forms the core before integrating [Link] or other frameworks.
• Prototyping: Ideal for testing and building proof-of-concept web systems.

❖ Advantages of [Link] HTTP Server :


• Fast and lightweight
• Built-in module (no installation required)
• Handles concurrent client requests efficiently
• Demonstrates core client-server interaction
• Forms the foundation for advanced backend frameworks
• Supports real-time applications

CONCLUSION :
Thus, a simple HTTP server was successfully created using [Link] built-in http module that
responds with
“Hello World” for every client request.
This practical helped us understand:
• The working of the http module in [Link]
• Creation of a basic web server
• Handling requests and responses manually
• Use of listen() method to start the server
Such servers form the foundation of backend web development, upon which advanced
frameworks like [Link] and [Link] are built.

Signature of Teacher

You might also like