Spaces:
Sleeping
Sleeping
Update index.js
Browse files
index.js
CHANGED
|
@@ -11,7 +11,9 @@ const io = socketIo(server, {
|
|
| 11 |
// Store connected users
|
| 12 |
const users = {};
|
| 13 |
|
| 14 |
-
app.
|
|
|
|
|
|
|
| 15 |
|
| 16 |
// Listen for connections
|
| 17 |
io.on('connection', (socket) => {
|
|
@@ -21,16 +23,16 @@ io.on('connection', (socket) => {
|
|
| 21 |
socket.on('user joined', (username, color) => {
|
| 22 |
users[socket.id] = { username, color };
|
| 23 |
console.log(`${username} has joined with color ${color}`);
|
| 24 |
-
//
|
| 25 |
io.emit('user joined', { username, color });
|
| 26 |
});
|
| 27 |
|
| 28 |
-
// Listen for messages
|
| 29 |
socket.on('message', (data) => {
|
| 30 |
const user = users[socket.id];
|
| 31 |
if (user) {
|
| 32 |
console.log(`Message received: ${data.msg} from ${user.username}`);
|
| 33 |
-
//
|
| 34 |
io.emit('message', { msg: data.msg, nick: user.username, color: user.color });
|
| 35 |
}
|
| 36 |
});
|
|
@@ -49,5 +51,5 @@ io.on('connection', (socket) => {
|
|
| 49 |
|
| 50 |
// Start the server
|
| 51 |
server.listen(7861, () => {
|
| 52 |
-
console.log('Server is running on http://localhost:
|
| 53 |
});
|
|
|
|
| 11 |
// Store connected users
|
| 12 |
const users = {};
|
| 13 |
|
| 14 |
+
app.get('/', (req, res) => {
|
| 15 |
+
res.send('Chat server is running. Connect via WebSocket.');
|
| 16 |
+
});
|
| 17 |
|
| 18 |
// Listen for connections
|
| 19 |
io.on('connection', (socket) => {
|
|
|
|
| 23 |
socket.on('user joined', (username, color) => {
|
| 24 |
users[socket.id] = { username, color };
|
| 25 |
console.log(`${username} has joined with color ${color}`);
|
| 26 |
+
// Notify all users that a new user has joined
|
| 27 |
io.emit('user joined', { username, color });
|
| 28 |
});
|
| 29 |
|
| 30 |
+
// Listen for messages using socket.send()
|
| 31 |
socket.on('message', (data) => {
|
| 32 |
const user = users[socket.id];
|
| 33 |
if (user) {
|
| 34 |
console.log(`Message received: ${data.msg} from ${user.username}`);
|
| 35 |
+
// Use socket.send to send messages back to all clients
|
| 36 |
io.emit('message', { msg: data.msg, nick: user.username, color: user.color });
|
| 37 |
}
|
| 38 |
});
|
|
|
|
| 51 |
|
| 52 |
// Start the server
|
| 53 |
server.listen(7861, () => {
|
| 54 |
+
console.log('Server is running on http://localhost:8086');
|
| 55 |
});
|