// Server-side code (app.js)
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const clients = {};
wss.on('connection', (ws) => {
ws.on('message', (message) => {
const messageObject = JSON.parse(message);
if (messageObject.name && messageObject.message) {
// Store the client's name
clients[ws] = messageObject.name;
// Broadcast the message to all connected clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(messageObject));
}
});
}
});
ws.on('close', () => {
// Remove the client from the list when they disconnect
delete clients[ws];
});
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});