-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathserver.js
More file actions
74 lines (61 loc) · 2.06 KB
/
server.js
File metadata and controls
74 lines (61 loc) · 2.06 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
/**
* @fileoverview Production server for QryptChat
* Integrates SvelteKit with WebSocket server for real-time chat functionality
*/
import { createServer } from 'node:http';
import { handler } from './build/handler.js';
import { WebSocketServer } from 'ws';
import { ChatWebSocketServer } from './src/lib/websocket/server.js';
import { messageCleanupService } from './src/lib/services/message-cleanup-service.js';
// Create HTTP server that delegates all non-WS requests to SvelteKit
const server = createServer((req, res) => {
// SvelteKit handles all HTTP requests
handler(req, res);
});
// Create WebSocket server in "noServer" mode for manual upgrade handling
const wss = new WebSocketServer({ noServer: true });
// Create our chat WebSocket server instance
const chatServer = new ChatWebSocketServer({
wss, // Pass the WebSocket server instance
noListen: true // Don't create its own server
});
// Handle WebSocket upgrade requests
server.on('upgrade', (request, socket, head) => {
// Only upgrade requests to /ws path
if (request.url !== '/ws') {
socket.destroy();
return;
}
// Handle the upgrade using our WebSocket server
wss.handleUpgrade(request, socket, head, (ws) => {
// Use our chat server's connection handler
chatServer.handleConnection(ws, request);
});
});
// Graceful shutdown handling
const shutdown = () => {
console.log('Shutting down server...');
// Stop message cleanup service
messageCleanupService.stop();
// Close WebSocket server
wss.close(() => {
console.log('WebSocket server closed');
});
// Close HTTP server
server.close(() => {
console.log('HTTP server closed');
process.exit(0);
});
};
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`🚀 QryptChat server running on http://localhost:${PORT}`);
console.log(`📡 WebSocket endpoint available at ws://localhost:${PORT}/ws`);
// Start message cleanup service after server is running
setTimeout(() => {
messageCleanupService.start();
}, 2000);
});