1tbfree commited on
Commit
90cf2c6
·
verified ·
1 Parent(s): c61425f

Update chat.js

Browse files
Files changed (1) hide show
  1. chat.js +12 -3
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
- // Listen for incoming connections
 
 
14
  io.on('connection', (socket) => {
15
  console.log('A user connected');
16
 
 
 
 
 
 
17
  // Listen for chat messages
18
  socket.on('chat message', (msg) => {
19
- io.emit('chat message', msg); // Broadcast the message to all clients
 
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 || 7860;
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
  });