-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (69 loc) · 2.85 KB
/
server.js
File metadata and controls
78 lines (69 loc) · 2.85 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const os = require('os');
const PORT = 8080;
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return 'localhost';
}
const server = http.createServer((req, res) => {
const clientIP = req.socket.remoteAddress;
const timestamp = new Date().toLocaleTimeString('en-US', { hour12: false });
// Remove query string from URL (e.g. /game.js?v=3.3.3 -> /game.js)
const urlPath = req.url.split('?')[0];
let filePath = '.' + urlPath;
if (filePath === './') {
filePath = './index.html';
}
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
console.log(`[${timestamp}] ❌ 404 | ${clientIP} | ${req.url} -> ${filePath}`);
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 - File Not Found</h1>', 'utf-8');
} else {
console.log(`[${timestamp}] ⚠️ 500 | ${clientIP} | ${req.url} | ${error.code}`);
res.writeHead(500);
res.end('Server Error: ' + error.code, 'utf-8');
}
} else {
const sizeKB = (content.length / 1024).toFixed(2);
console.log(`[${timestamp}] ✅ 200 | ${clientIP} | ${req.url} -> ${filePath} | ${sizeKB} KB`);
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
server.listen(PORT, '0.0.0.0', () => {
const localIP = getLocalIP();
console.log('\n🎮 Math Wizard Game Server');
console.log('════════════════════════════════════════');
console.log(`Local: http://localhost:${PORT}`);
console.log(`Network: http://${localIP}:${PORT}`);
console.log('════════════════════════════════════════');
console.log('\n📱 On iPhone/iPad open:');
console.log(` http://${localIP}:${PORT}`);
console.log('\n⚠️ Make sure both devices are on the same WiFi network\n');
console.log('Press Ctrl+C to stop the server\n');
});