Spaces:
Sleeping
Sleeping
Create index.js
Browse files
index.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const http = require('http');
|
| 3 |
+
const socketIo = require('socket.io');
|
| 4 |
+
|
| 5 |
+
const app = express();
|
| 6 |
+
const server = http.createServer(app);
|
| 7 |
+
const io = socketIo(server, {
|
| 8 |
+
path: '/socket.io/',
|
| 9 |
+
});
|
| 10 |
+
|
| 11 |
+
// Store connected users
|
| 12 |
+
const users = {};
|
| 13 |
+
|
| 14 |
+
app.use(express.static('public')); // Serve static files from the 'public' directory
|
| 15 |
+
|
| 16 |
+
// Listen for connections
|
| 17 |
+
io.on('connection', (socket) => {
|
| 18 |
+
console.log('A user connected:', socket.id);
|
| 19 |
+
|
| 20 |
+
// Listen for user joining
|
| 21 |
+
socket.on('user joined', (username, color) => {
|
| 22 |
+
users[socket.id] = { username, color };
|
| 23 |
+
console.log(`${username} has joined with color ${color}`);
|
| 24 |
+
// Broadcast to all users that a new user has joined
|
| 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 |
+
// Broadcast the message to all users
|
| 34 |
+
io.emit('message', { msg: data.msg, nick: user.username, color: user.color });
|
| 35 |
+
}
|
| 36 |
+
});
|
| 37 |
+
|
| 38 |
+
// Handle disconnection
|
| 39 |
+
socket.on('disconnect', () => {
|
| 40 |
+
const user = users[socket.id];
|
| 41 |
+
if (user) {
|
| 42 |
+
console.log(`${user.username} has disconnected`);
|
| 43 |
+
// Notify others that this user has left
|
| 44 |
+
io.emit('user left', { username: user.username });
|
| 45 |
+
delete users[socket.id];
|
| 46 |
+
}
|
| 47 |
+
});
|
| 48 |
+
});
|
| 49 |
+
|
| 50 |
+
// Start the server
|
| 51 |
+
server.listen(7861, () => {
|
| 52 |
+
console.log('Server is running on http://localhost:7861');
|
| 53 |
+
});
|