How to Create a Chat Room Using WebSocket on Node.js
In this article, we will dive into the practical aspects of creating a real-time chat room using WebSocket on Node.js. WebSockets provide a full-duplex communication channel over a single TCP connection, making them ideal for chat applications. Let’s get started!
Prerequisites
Before we begin, ensure you have the following installed:
- Node.js (version 12 or higher)
- npm (Node Package Manager)
Step 1: Setting Up Your Project
Create a new directory for your project and navigate into it:
```
mkdir websocket-chat
cd websocket-chat
```
Initialize a new Node.js project:
```
npm init -y
```
Now, install the necessary packages:
```
npm install express ws
```
- express: A web framework for Node.js.
- ws: A simple WebSocket library for Node.js.
Step 2: Creating the Server
Create a new file named `server.js` and add the following code:
```javascript
const express = require('express');
const WebSocket = require('ws');
const http = require('http');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
app.use(express.static('public'));
wss.on('connection', (ws) => {
console.log('New client connected');
ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Broadcast the message to all clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
```
This code sets up an Express server and a WebSocket server. When a client connects, it listens for messages and broadcasts them to all connected clients.
Step 3: Creating the Client
Create a new directory named `public` and inside it, create an `index.html` file:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Chat Room</title>
<style>
body { font-family: Arial, sans-serif; }
#messages { list-style-type: none; padding: 0; }
#messages li { padding: 8px; margin: 5px; background: #f1f1f1; }
</style>
</head>
<body>
<h1>WebSocket Chat Room</h1>
<ul id="messages"></ul>
<input id="messageInput" autocomplete="off" /><button id="sendButton">Send</button>
<script>
const ws = new WebSocket('ws://localhost:3000');
ws.onmessage = (event) => {
const messages = document.getElementById('messages');
const messageItem = document.createElement('li');
messageItem.textContent = event.data;
messages.appendChild(messageItem);
};
document.getElementById('sendButton').onclick = () => {
const input = document.getElementById('messageInput');
ws.send(input.value);
input.value = '';
};
</script>
</body>
</html>
```
This HTML file creates a simple chat interface. It connects to the WebSocket server and allows users to send and receive messages.
Step 4: Running the Application
Now that everything is set up, run your server:
```
node server.js
```
Open your browser and navigate to . Open multiple tabs to test the chat functionality. You should be able to send messages between the tabs in real-time!
Conclusion
Congratulations! You have successfully created a simple chat room using WebSocket on Node.js. This basic implementation can be expanded with features like user authentication, message history, and more.
Feel free to experiment and enhance your