-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
327 lines (281 loc) · 8.55 KB
/
server.js
File metadata and controls
327 lines (281 loc) · 8.55 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
const express = require("express")
const http = require("http")
const WebSocket = require("ws")
const { v4: uuidv4 } = require("uuid")
const path = require("path")
const app = express()
const server = http.createServer(app)
const wss = new WebSocket.Server({ server })
// Serve static files from 'public' directory
app.use(express.static(path.join(__dirname, "public")))
// Handle all routes with the single HTML file
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"))
})
// WebSocket Session Management
const streams = new Map()
const sessionTimeouts = new Map()
// Clean up inactive sessions after 30 minutes
const SESSION_TIMEOUT = 30 * 60 * 1000 // 30 minutes
wss.on("connection", (ws, req) => {
let sessionId = null
let isHost = false
const clientId = uuidv4()
console.log(`Client connected: ${clientId}`)
ws.on("message", (message) => {
try {
// Handle binary data (video stream)
if (Buffer.isBuffer(message)) {
if (isHost && streams.has(sessionId)) {
const session = streams.get(sessionId)
// Broadcast to all viewers
session.viewers.forEach((viewer) => {
if (viewer.ws.readyState === WebSocket.OPEN) {
try {
viewer.ws.send(message)
} catch (error) {
console.error(`Failed to send to viewer ${viewer.id}:`, error)
session.viewers.delete(viewer)
}
}
})
}
return
}
// Handle JSON control messages
const data = JSON.parse(message)
console.log(`Message from ${clientId}:`, data.type)
switch (data.type) {
case "start":
handleStartSession(ws, data, clientId)
break
case "join":
handleJoinSession(ws, data, clientId)
break
case "stop":
handleStopSession(sessionId)
break
default:
console.log(`Unknown message type: ${data.type}`)
}
} catch (error) {
console.error(`Error processing message from ${clientId}:`, error)
ws.send(
JSON.stringify({
type: "error",
message: "Invalid message format",
}),
)
}
})
ws.on("error", (error) => {
console.error(`WebSocket error for ${clientId}:`, error)
})
ws.on("close", () => {
console.log(`Client disconnected: ${clientId}`)
handleClientDisconnect()
})
function handleStartSession(ws, data, clientId) {
sessionId = data.sessionId || uuidv4()
isHost = true
// Create new session
streams.set(sessionId, {
host: { ws, id: clientId },
viewers: new Set(),
createdAt: Date.now(),
})
// Clear any existing timeout
if (sessionTimeouts.has(sessionId)) {
clearTimeout(sessionTimeouts.get(sessionId))
sessionTimeouts.delete(sessionId)
}
ws.send(
JSON.stringify({
type: "sessionCreated",
sessionId: sessionId,
}),
)
console.log(`Session started: ${sessionId} by ${clientId}`)
updateViewerCount(sessionId)
}
function handleJoinSession(ws, data, clientId) {
sessionId = data.sessionId
if (!streams.has(sessionId)) {
ws.send(
JSON.stringify({
type: "error",
message: "Session not found or has ended",
}),
)
ws.close()
return
}
const session = streams.get(sessionId)
session.viewers.add({ ws, id: clientId })
ws.send(
JSON.stringify({
type: "joined",
sessionId: sessionId,
}),
)
console.log(`Viewer joined session: ${sessionId} (${clientId})`)
updateViewerCount(sessionId)
}
function handleStopSession(sessionId) {
if (streams.has(sessionId)) {
const session = streams.get(sessionId)
// Notify all viewers
session.viewers.forEach((viewer) => {
if (viewer.ws.readyState === WebSocket.OPEN) {
try {
viewer.ws.send(
JSON.stringify({
type: "sessionEnded",
}),
)
viewer.ws.close()
} catch (error) {
console.error(`Failed to notify viewer ${viewer.id}:`, error)
}
}
})
streams.delete(sessionId)
console.log(`Session terminated: ${sessionId}`)
}
}
function handleClientDisconnect() {
if (isHost && sessionId && streams.has(sessionId)) {
// Host disconnected, terminate session
handleStopSession(sessionId)
} else if (sessionId && streams.has(sessionId)) {
// Viewer disconnected, remove from session
const session = streams.get(sessionId)
session.viewers.forEach((viewer) => {
if (viewer.id === clientId) {
session.viewers.delete(viewer)
}
})
updateViewerCount(sessionId)
}
}
function updateViewerCount(sessionId) {
if (!streams.has(sessionId)) return
const session = streams.get(sessionId)
const count = session.viewers.size
// Send to host
if (session.host.ws.readyState === WebSocket.OPEN) {
try {
session.host.ws.send(
JSON.stringify({
type: "viewerCount",
count: count,
}),
)
} catch (error) {
console.error(`Failed to send viewer count to host:`, error)
}
}
// Send to all viewers
session.viewers.forEach((viewer) => {
if (viewer.ws.readyState === WebSocket.OPEN) {
try {
viewer.ws.send(
JSON.stringify({
type: "viewerCount",
count: count,
}),
)
} catch (error) {
console.error(`Failed to send viewer count to viewer ${viewer.id}:`, error)
session.viewers.delete(viewer)
}
}
})
}
})
// Cleanup inactive sessions periodically
setInterval(
() => {
const now = Date.now()
streams.forEach((session, sessionId) => {
if (now - session.createdAt > SESSION_TIMEOUT) {
console.log(`Cleaning up inactive session: ${sessionId}`)
// Notify viewers
session.viewers.forEach((viewer) => {
if (viewer.ws.readyState === WebSocket.OPEN) {
try {
viewer.ws.send(
JSON.stringify({
type: "sessionEnded",
}),
)
viewer.ws.close()
} catch (error) {
console.error(`Failed to notify viewer during cleanup:`, error)
}
}
})
// Close host connection
if (session.host.ws.readyState === WebSocket.OPEN) {
try {
session.host.ws.close()
} catch (error) {
console.error(`Failed to close host connection during cleanup:`, error)
}
}
streams.delete(sessionId)
}
})
},
5 * 60 * 1000,
) // Check every 5 minutes
// Health check endpoint
app.get("/health", (req, res) => {
res.json({
status: "healthy",
activeSessions: streams.size,
uptime: process.uptime(),
})
})
// Use environment PORT for deployment platforms like Render, Heroku, etc.
const PORT = process.env.PORT || 3000
const HOST = "0.0.0.0"
server.listen(PORT, HOST, () => {
console.log(`Server running at http://localhost:${PORT}`)
console.log(`Environment: ${process.env.NODE_ENV || "development"}`)
console.log(`WebSocket server initialized`)
})
// Graceful shutdown
process.on("SIGTERM", () => {
console.log("Shutting down server gracefully...")
// Close all WebSocket connections
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(
JSON.stringify({
type: "serverShutdown",
message: "Server is shutting down",
}),
)
client.close()
}
})
// Close HTTP server
server.close(() => {
console.log("Server shutdown complete")
process.exit(0)
})
})
process.on("SIGINT", () => {
console.log("Received SIGINT, shutting down gracefully...")
process.emit("SIGTERM")
})
// Handle uncaught exceptions
process.on("uncaughtException", (error) => {
console.error("Uncaught Exception:", error)
process.exit(1)
})
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled Rejection at:", promise, "reason:", reason)
process.exit(1)
})