-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
101 lines (76 loc) · 2.73 KB
/
server.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import express from 'express';
const app = express();
import http from 'http';
import path from 'path';
import { Server } from 'socket.io';
import { fileURLToPath } from 'url';
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: '*',
}
});
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.use(express.static('dist'))
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'))
})
const rooms = {};
io.on('connection', (socket) => {
console.log('New client connected:', socket.id);
socket.on('join', ({ roomId, username }) => {
socket.data.username = username;
socket.join(roomId);
if (!username || username.trim() === '') {
socket.emit('join-error', 'Username is required');
return;
}
if (!rooms[roomId]) {
rooms[roomId] = { clients: {} };
}
delete rooms[roomId].clients[username];
rooms[roomId].clients[username] = { socketId: socket.id, username };
const clientList = Object.values(rooms[roomId].clients);
io.to(roomId).emit('join', {
clients: clientList,
username,
socketId: socket.id,
});
console.log(`${username} joined room ${roomId}`);
console.log('Existing clients in room:', clientList);
});
socket.on('code-change', ({ roomId, code }) => {
socket.in(roomId).emit('code-change', { code });
});
socket.on('sync-code', ({ socketId, code }) => {
io.to(socketId).emit('code-change', { code });
});
socket.on('language:change', ({ roomId, language }) => {
socket.in(roomId).emit('language:change', { language });
});
socket.on('output-details', ({ roomId, outputDetails }) => {
socket.in(roomId).emit('output-details', { outputDetails });
});
socket.on('disconnecting', () => {
const rooms = Object.keys(socket.rooms);
rooms.forEach((roomId) => {
if (roomId !== socket.id) {
const room = rooms[roomId];
const clientUsername = socket.data.username;
delete room.clients[clientUsername];
const clientList = Object.values(room.clients);
io.to(roomId).emit('join', {
clients: clientList,
username: clientUsername,
socketId: socket.id,
});
}
});
});
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Listening on port ${PORT}`));