-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
82 lines (67 loc) · 2.21 KB
/
server.ts
File metadata and controls
82 lines (67 loc) · 2.21 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
import { createServer } from 'http';
import { parse } from 'url';
import next from 'next';
import { WebSocketServer, WebSocket } from 'ws';
const dev = process.env.NODE_ENV !== 'production';
const hostname = 'localhost';
const port = 3001;
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url!, true);
await handle(req, res, parsedUrl);
} catch (err) {
console.error('Error occurred handling', req.url, err);
res.statusCode = 500;
res.end('Internal server error');
}
});
// Create WebSocket server with dedicated path
const wss = new WebSocketServer({ server, path: '/ws' });
console.log('WebSocket server initialized');
wss.on('connection', (ws: WebSocket) => {
console.log('Client connected to WebSocket');
ws.on('message', (message: Buffer) => {
try {
const data = JSON.parse(message.toString());
console.log('Received message from client:', data);
// Echo back or handle client messages if needed
// For now, we mainly broadcast from API routes
} catch (error) {
console.error('Error parsing WebSocket message:', error);
}
});
ws.on('close', () => {
console.log('Client disconnected from WebSocket');
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
// Send initial connection confirmation
ws.send(JSON.stringify({
type: 'connection',
status: 'connected',
timestamp: new Date().toISOString(),
}));
});
// Export broadcast function for use in API routes
global.wsBroadcast = (data: any) => {
const message = JSON.stringify(data);
let sentCount = 0;
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
sentCount++;
}
});
if (sentCount > 0) {
console.log(`Broadcast to ${sentCount} client(s):`, data.type);
}
};
server.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
console.log(`> WebSocket ready on ws://${hostname}:${port}`);
});
});