Implementing a WebSocket chat application in Node.js involves creating a server that can handle WebSocket connections and managing the communication between clients. Here's a simple example using the ws
library, which is a popular WebSocket library for Node.js:
Setup:
Make sure you have Node.js installed on your machine. You can create a new project directory and initialize it with npm init
.
Install the ws
library:
bashnpm install ws
Server Implementation:
Create a file named server.js
:
javascriptconst WebSocket = require('ws');
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
// Connection is established
console.log('Client connected');
// Handle messages from clients
ws.on('message', (message) => {
// Broadcast the message to all clients
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// Handle disconnection
ws.on('close', () => {
console.log('Client disconnected');
});
});
// Serve static files (optional)
app.use(express.static('public'));
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
This code creates an HTTP server using Express and integrates the WebSocket server using the ws
library. It broadcasts messages to all connected clients.
Client Implementation:
Create an HTML file named index.html
:
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</title>
</head>
<body>
<input type="text" id="messageInput" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
<ul id="chat"></ul>
<script>
const socket = new WebSocket('ws://localhost:3000');
socket.addEventListener('message', (event) => {
const chat = document.getElementById('chat');
const listItem = document.createElement('li');
listItem.textContent = event.data;
chat.appendChild(listItem);
});
function sendMessage() {
const messageInput = document.getElementById('messageInput');
const message = messageInput.value;
socket.send(message);
messageInput.value = '';
}
</script>
</body>
</html>
This simple HTML file includes a text input for typing messages, a "Send" button, and a list to display the chat messages. The JavaScript code connects to the WebSocket server and handles sending and receiving messages.
Run the Application:
Run your server using:
bashnode server.js
Open your browser and visit http://localhost:3000
(or the port you specified). Open multiple browser tabs or windows to simulate different clients and see the real-time chat in action.
This is a basic example, and you may want to add features like user authentication, room management, or message persistence based on your application requirements.