Spaces:
Sleeping
Sleeping
File size: 1,846 Bytes
167527c 3ac3a30 167527c 3ac3a30 f2b2d33 3ac3a30 f2b2d33 167527c f2b2d33 167527c f2b2d33 167527c f2b2d33 167527c f689c12 3ac3a30 167527c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
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');
});
|