Table of Contents
Real-time applications have become essential in today's web development landscape, enabling instant communication between users and servers. This tutorial guides you through building a simple real-time chat application using Express.js and WebSocket integration.
Prerequisites
- Node.js installed on your machine
- Basic knowledge of JavaScript and Node.js
- Text editor or IDE (e.g., VS Code)
- Terminal or command prompt access
Setting Up the Project
Create a new directory for your project and initialize it with npm:
mkdir real-time-chat
cd real-time-chat
npm init -y
Install the necessary dependencies:
npm install express ws
Creating the Server
In the root directory, create a file named server.js and add the following code:
const express = require('express');
const WebSocket = require('ws');
const app = express();
const port = 3000;
app.use(express.static('public'));
const server = app.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
});
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('New client connected');
ws.on('message', (message) => {
// Broadcast message to all clients
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
Creating the Client
Create a public directory in your project folder. Inside it, create an index.html file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Chat</title>
<style>
body { font-family: Arial, sans-serif; }
#messages { border: 1px solid #ccc; height: 300px; overflow-y: scroll; padding: 10px; }
#input { width: 80%; }
#send { width: 15%; }
</style>
</head>
<body>
<h2>Real-Time Chat</h2>
<div id="messages"></div>
<input type="text" id="input" placeholder="Type a message...">
<button id="send">Send</button>
<script>
const ws = new WebSocket('ws://localhost:3000');
const messages = document.getElementById('messages');
const input = document.getElementById('input');
const sendButton = document.getElementById('send');
ws.onmessage = (event) => {
const message = document.createElement('div');
message.textContent = event.data;
messages.appendChild(message);
messages.scrollTop = messages.scrollHeight;
};
sendButton.onclick = () => {
if (input.value) {
ws.send(input.value);
input.value = '';
}
};
input.addEventListener('keyup', (event) => {
if (event.key === 'Enter') {
sendButton.click();
}
});
</script>
</body>
</html>
Running the Application
Start the server by running:
node server.js
Open your browser and navigate to http://localhost:3000/index.html. Open multiple tabs or browsers to test real-time messaging.
Conclusion
You've successfully set up a basic real-time chat application using Express.js and WebSocket. This foundation can be expanded for more complex applications like live notifications, collaborative tools, and more.