Update chat.js
Browse files
chat.js
CHANGED
@@ -10,23 +10,32 @@ const io = socketIo(server);
|
|
10 |
// Serve static files from the "public" directory
|
11 |
app.use(express.static('public'));
|
12 |
|
13 |
-
//
|
|
|
|
|
14 |
io.on('connection', (socket) => {
|
15 |
console.log('A user connected');
|
16 |
|
|
|
|
|
|
|
|
|
|
|
17 |
// Listen for chat messages
|
18 |
socket.on('chat message', (msg) => {
|
19 |
-
|
|
|
20 |
});
|
21 |
|
22 |
// Handle disconnection
|
23 |
socket.on('disconnect', () => {
|
24 |
console.log('A user disconnected');
|
|
|
25 |
});
|
26 |
});
|
27 |
|
28 |
// Start the server
|
29 |
-
const PORT = process.env.PORT ||
|
30 |
server.listen(PORT, () => {
|
31 |
console.log(`Server is running on http://localhost:${PORT}`);
|
32 |
});
|
|
|
10 |
// Serve static files from the "public" directory
|
11 |
app.use(express.static('public'));
|
12 |
|
13 |
+
// Store usernames associated with socket IDs
|
14 |
+
const usernames = {};
|
15 |
+
|
16 |
io.on('connection', (socket) => {
|
17 |
console.log('A user connected');
|
18 |
|
19 |
+
// Handle setting the username
|
20 |
+
socket.on('set username', (username) => {
|
21 |
+
usernames[socket.id] = username;
|
22 |
+
});
|
23 |
+
|
24 |
// Listen for chat messages
|
25 |
socket.on('chat message', (msg) => {
|
26 |
+
const username = usernames[socket.id] || 'Anonymous';
|
27 |
+
io.emit('chat message', { username, message: msg }); // Broadcast the message with username
|
28 |
});
|
29 |
|
30 |
// Handle disconnection
|
31 |
socket.on('disconnect', () => {
|
32 |
console.log('A user disconnected');
|
33 |
+
delete usernames[socket.id]; // Remove username on disconnect
|
34 |
});
|
35 |
});
|
36 |
|
37 |
// Start the server
|
38 |
+
const PORT = process.env.PORT || 3000;
|
39 |
server.listen(PORT, () => {
|
40 |
console.log(`Server is running on http://localhost:${PORT}`);
|
41 |
});
|