generated from google-gemini/aistudio-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
37 lines (31 loc) · 1.08 KB
/
server.js
File metadata and controls
37 lines (31 loc) · 1.08 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
/**
* CAVERN PVP - SIGNALING SERVER (TCP)
*
* To run:
* 1. npm install ws
* 2. node server.js
*
* This server uses TCP (WebSockets) to facilitate the initial handshake (Signaling).
* Once clients connect, they establish a DIRECT UDP (WebRTC) connection for the game.
*/
const WebSocket = require('ws');
const PORT = 8080;
const wss = new WebSocket.Server({ port: PORT });
console.log(`[SIGNALING] Server running on port ${PORT}`);
console.log(`[SIGNALING] Ready to bootstrap UDP connections.`);
wss.on('connection', function connection(ws, req) {
const ip = req.socket.remoteAddress;
console.log(`[CONN] New client connected from ${ip}`);
ws.on('message', function incoming(message) {
// Broadcast to all other clients to find peers
// In a production app, we would target specific IDs, but for 2-player LAN, broadcast is fine.
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => {
console.log(`[DISC] Client disconnected`);
});
});