-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
272 lines (225 loc) · 8.23 KB
/
Copy pathserver.js
File metadata and controls
272 lines (225 loc) · 8.23 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import { createServer } from 'http';
import { parse } from 'url';
import next from 'next';
import { Server } from 'socket.io';
const dev = process.env.NODE_ENV !== 'production';
const hostname = dev ? 'localhost' : '0.0.0.0';
const port = parseInt(process.env.PORT || '3000', 10);
const app = next({ dev, hostname, port });
const handler = app.getRequestHandler();
// Store room states, connections, and sync intervals
const roomStates = new Map();
const roomConnections = new Map();
const roomSyncIntervals = new Map();
app.prepare().then(() => {
const server = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url, true);
await handler(req, res, parsedUrl);
} catch (err) {
console.error('Error occurred handling', req.url, err);
res.statusCode = 500;
res.end('internal server error');
}
});
// Initialize Socket.IO
const io = new Server(server, {
cors: {
origin: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : '*',
methods: ['GET', 'POST'],
credentials: true
},
pingTimeout: 60000,
pingInterval: 25000,
transports: ['websocket', 'polling']
});
io.on('connection', (socket) => {
console.log('🔌 Client connected:', socket.id);
// Join room
socket.on('join-room', ({ roomId, username }) => {
socket.join(roomId);
if (!roomConnections.has(roomId)) {
roomConnections.set(roomId, new Set());
}
roomConnections.get(roomId).add(socket.id);
// Send server time for clock sync
const serverTime = Date.now();
socket.emit('server-time', { serverTime });
console.log(`👤 ${username} (${socket.id}) joined room: ${roomId}`);
// Notify others in room
socket.to(roomId).emit('user-joined', {
userId: socket.id,
username,
timestamp: serverTime
});
// Send current room state to new user
if (roomStates.has(roomId)) {
const state = roomStates.get(roomId);
socket.emit('room-state', state);
// If music is playing, send current position immediately
if (state.isPlaying && state.lastCommandTime) {
const elapsedTime = (Date.now() - state.lastCommandTime) / 1000;
const currentPosition = (state.currentTime || 0) + elapsedTime;
socket.emit('playback-sync', {
command: 'play',
data: {
isPlaying: true,
currentTime: currentPosition
},
scheduledTime: Date.now() + 30,
serverTime: Date.now(),
initiatedBy: 'system'
});
console.log(`📍 Syncing new user to current position: ${currentPosition.toFixed(2)}s`);
}
}
// Start periodic sync for this room (if not already started)
startRoomSync(roomId);
});
// Periodic room state sync to keep all clients aligned
function startRoomSync(roomId) {
// Check if sync already running for this room
if (roomSyncIntervals.has(roomId)) return;
const syncInterval = setInterval(() => {
const state = roomStates.get(roomId);
if (!state || !state.isPlaying) return;
// Calculate current playback position
const elapsedTime = (Date.now() - (state.lastCommandTime || Date.now())) / 1000;
const currentPosition = (state.currentTime || 0) + elapsedTime;
// Broadcast current position to all clients every 2 seconds
io.to(roomId).emit('position-sync', {
currentTime: currentPosition,
serverTime: Date.now(),
isPlaying: state.isPlaying
});
console.log(`🔄 [${roomId}] Position sync: ${currentPosition.toFixed(2)}s`);
}, 2000); // Every 2 seconds
roomSyncIntervals.set(roomId, syncInterval);
console.log(`▶️ Started periodic sync for room: ${roomId}`);
}
// High-precision clock synchronization
socket.on('clock-sync', ({ clientTime }) => {
// Respond immediately with minimal processing delay
const serverTime = Date.now();
socket.emit('clock-sync-response', {
clientTime,
serverTime,
serverProcessingTime: Date.now() - serverTime // Should be < 1ms
});
});
// Playback control events with ULTRA-PRECISE timing and conflict resolution
socket.on('playback-command', ({ roomId, command, timestamp, scheduledTime, data, initiatedBy }) => {
const serverTime = Date.now();
const delayMs = scheduledTime - serverTime;
console.log(`🎮 [${initiatedBy}] ${command} command in ${roomId}, scheduled in ${delayMs.toFixed(1)}ms`);
// Store room state with last action metadata
const state = roomStates.get(roomId) || {};
roomStates.set(roomId, {
...state,
...data,
lastCommand: command,
lastCommandBy: initiatedBy,
lastCommandTime: serverTime
});
// Broadcast to ALL clients (including sender for consistency)
// Use exact scheduled time - already adjusted for network latency
io.to(roomId).emit('playback-sync', {
command,
data,
timestamp,
scheduledTime, // ULTRA-PRECISE scheduled time
serverTime,
initiatedBy
});
});
// Seek event with ULTRA-PRECISE sync (15ms window)
socket.on('seek-command', ({ roomId, time, username }) => {
const serverTime = Date.now();
const scheduledTime = serverTime + 15; // ULTRA-tight 15ms sync window
console.log(`⏩ [${username}] Seek to ${time.toFixed(2)}s in ${roomId}, scheduled in 15ms`);
// Update room state
const state = roomStates.get(roomId) || {};
roomStates.set(roomId, {
...state,
currentTime: time,
lastSeekTime: serverTime,
lastSeekBy: username
});
// Broadcast to ALL clients including sender for perfect sync
io.to(roomId).emit('seek-sync', {
time,
scheduledTime,
serverTime,
initiatedBy: username
});
});
// Volume change
socket.on('volume-change', ({ roomId, volume, username }) => {
console.log(`🔊 Volume change in ${roomId}: ${volume}`);
socket.to(roomId).emit('volume-sync', {
volume,
changedBy: username,
timestamp: Date.now()
});
});
// Playlist update
socket.on('playlist-updated', ({ roomId, playlist }) => {
console.log(`📝 Playlist updated in ${roomId}, songs: ${playlist.length}`);
socket.to(roomId).emit('playlist-sync', {
playlist,
timestamp: Date.now()
});
});
// Leave room
socket.on('leave-room', ({ roomId, username }) => {
socket.leave(roomId);
if (roomConnections.has(roomId)) {
roomConnections.get(roomId).delete(socket.id);
if (roomConnections.get(roomId).size === 0) {
roomConnections.delete(roomId);
roomStates.delete(roomId);
}
}
console.log(`👋 ${username} left room: ${roomId}`);
socket.to(roomId).emit('user-left', {
userId: socket.id,
username,
timestamp: Date.now()
});
});
// Disconnect
socket.on('disconnect', () => {
console.log('🔌 Client disconnected:', socket.id);
// Clean up room connections
for (const [roomId, connections] of roomConnections.entries()) {
if (connections.has(socket.id)) {
connections.delete(socket.id);
if (connections.size === 0) {
roomConnections.delete(roomId);
roomStates.delete(roomId);
}
io.to(roomId).emit('user-disconnected', {
userId: socket.id,
timestamp: Date.now()
});
}
}
});
// Heartbeat for latency monitoring
socket.on('heartbeat', ({ clientTime }) => {
socket.emit('heartbeat-response', {
clientTime,
serverTime: Date.now()
});
});
});
server
.once('error', (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
console.log('> Socket.IO server running for real-time sync');
});
});