To build a live chat application, you need to use Node.js and WebSocket to achieve full duplex communication. The specific steps are as follows: 1. Initialize the Node.js project and install the ws library, create a server.js file, set up the WebSocket server to listen to port 8080, maintain the client connection collection, and broadcast it to all clients when receiving the message; 2. Create an index.html front-end page, including the message display area, input box and send button, establish a connection with the WebSocket server through JavaScript, dynamically add it to the page when receiving the message, and support clicking sending or pressing Enter to submit; 3. Modify server.js to integrate HTTP server functions, use Node.js' built-in http, fs and path modules to read and respond to index.html file requests, so that the same server can provide both web pages and handle WebSocket connections; 4. After starting the server, visit http://localhost:8080 in multiple browser tags, and messages sent by any tag will be synchronized to other tags in real time. At this point, a basic but complete live chat application has been implemented, and can subsequently expand features such as nickname, timestamp, private chat, reconnection mechanism and input purification. This solution demonstrates the core mechanism of real-time communication with concise code, laying the foundation for more complex applications.

Building a real-time chat app with WebSockets and Node.js is a practical way to learn full-duplex communication on the web. Unlike traditional HTTP, where the client requests and the server responses, WebSockets allows both sides to send data at any time—perfect for instant messaging.

Here's how to build a simple but functional real-time chat app using Node.js and the ws
library.
1. Set Up the Node.js Server with WebSockets
Start by initializing a Node.js project and installing the ws
package:

npm init -y
npm install ws
Create a file called server.js
. This will handle WebSocket connections and message broadcasting.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const clients = new Set();
wss.on('connection', (ws) => {
clients.add(ws);
console.log('Client connected');
ws.on('message', (data) => {
// Broadcast message to all connected clients
for (let client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
}
});
ws.on('close', () => {
clients.delete(ws);
console.log('Client disconnected');
});
});
console.log('WebSocket server is running on ws://localhost:8080');
This server listens on port 8080, keeps track of connected clients, and broadcasts any received message to all of them.

2. Create a Simple Frontend HTML Page
Create an index.html
file to serve as the chat interface.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Real-Time Chat</title>
<style>
#messages { height: 300px; overflow-y: scroll; border: 1px solid #ccc; margin-bottom: 10px; padding: 10px; }
#input { width: 80%; padding: 10px; }
#send { width: 15%; padding: 10px; }
</style>
</head>
<body>
<h2>Chat Room</h2>
<div id="messages"></div>
<input type="text" id="input" placeholder="Type a message..." />
<button id="send">Send</button>
<script>
const socket = new WebSocket('ws://localhost:8080');
const messages = document.getElementById('messages');
const input = document.getElementById('input');
const sendButton = document.getElementById('send');
// Display incoming messages
socket.onmessage = (event) => {
const message = document.createElement('div');
message.textContent = event.data;
messages.appendChild(message);
messages.scrollTop = messages.scrollHeight;
};
// Send message on button click or Enter key
sendButton.onclick = () => {
if (input.value.trim()) {
socket.send(input.value);
input.value = '';
}
};
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendButton.click();
});
</script>
</body>
</html>
This page connects to the WebSocket server, displays received messages, and sends user input when the "Send" button is clicked or Enter is pressed.
3. Serve the HTML File
The current server only handles WebSocket connections. To serve index.html
, you need an HTTP server. Update server.js
to include static file serving:
const http = require('http');
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');
// Create HTTP server
const server = http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
if (err) {
res.writeHead(500);
res.end('Error loading index.html');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else {
res.writeHead(404);
res.end();
}
});
// Attach WebSocket server to the same port
const wss = new WebSocket.Server({ server });
const clients = new Set();
wss.on('connection', (ws) => {
clients.add(ws);
console.log('Client connected');
ws.on('message', (data) => {
for (let client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(data.toString());
}
}
});
ws.on('close', () => {
clients.delete(ws);
console.log('Client disconnected');
});
});
server.listen(8080, () => {
console.log('Server running on http://localhost:8080');
});
Now the same server serves the webpage and handles WebSocket connections.
4. Run and Test the App
Start the server:
node server.js
Open multiple browser tabs to http://localhost:8080
Type a message in one tab—it should appear instantly in all others
You now have a working real-time chat app.
Optional Improvements
To make this more robust, consider adding:
- User nicknames : Send metadata along with messages
- Message timestamps : Format and display when messages were sent
- Private message : Route messages to specific clients using IDs
- Reconnection logic : Handle network drops gracefully
- Input sanitization : Prevent XSS by escaping HTML in messages
That's it. With just a few dozen lines of code, you've built a real-time chat app using WebSockets and Node.js. The core idea—broadcasting messages to all connected clients—is the foundation of most chat systems. From here, you can scale up with rooms, authentication, or databases. Basically, this is the minimum viable version that actually works.
The above is the detailed content of Building a Real-Time Chat App with WebSockets and Node.js. For more information, please follow other related articles on the PHP Chinese website!