const express = require('express'); const http = require('http'); const socketIo = require('socket.io'); const path = require('path'); const app = express(); const server = http.createServer(app); const io = socketIo(server, { path: '/socket.io/', }); // Store connected users const users = {}; // Serve static files from the public directory app.use(express.static(path.join(__dirname, 'public'))); // Route to serve the index.html file app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); // Listen for connections io.on('connection', (socket) => { console.log('A user connected:', socket.id); // Listen for user joining socket.on('user joined', (username, color) => { users[socket.id] = { username, color }; console.log(`${username} has joined with color ${color}`); // Notify all users that a new user has joined io.emit('user joined', { username, color }); }); // Listen for messages using socket.send() socket.on('message', (data) => { const user = users[socket.id]; if (user) { console.log(`Message received: ${data.msg} from ${user.username}`); // Use socket.send to send messages back to all clients io.emit('message', { msg: data.msg, nick: user.username, color: user.color }); } }); // Handle disconnection socket.on('disconnect', () => { const user = users[socket.id]; if (user) { console.log(`${user.username} has disconnected`); // Notify others that this user has left io.emit('user left', { username: user.username }); delete users[socket.id]; } }); }); // Start the server server.listen(7860, () => { console.log('Server is running on http://localhost:7860'); });