Files
justice/www/html/Game/public/trycss/game-justic2/gateway.js
T
2026-05-26 10:48:16 +00:00

178 lines
6.2 KiB
JavaScript

/**
* gateway.js — Standalone dev server for game-justic2
*
* เสิร์ฟทุกไฟล์ใน project นี้เป็น "site root" (เพราะ client ใช้
* absolute path เช่น /Login/, /Main-Lobby/, /Game/, /realtimechat/)
* และ proxy ทราฟฟิก HTTP+WebSocket ไปยัง Node game/chat servers:
* - /Game/* → 127.0.0.1:GAME_PORT (default 3004)
* - /realtimechat/* → 127.0.0.1:CHAT_PORT (default 3003)
*
* ใช้งาน: node gateway.js
* เปิดเว็บ: http://localhost:8080/ (เด้งไป /Login/ อัตโนมัติ)
*
* ตั้งค่า port ผ่าน env:
* set GATEWAY_PORT=80 (ต้องปิด WAMP/Apache ก่อน)
* set GAME_PORT=3004
* set CHAT_PORT=3003
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const net = require('net');
const GATEWAY_PORT = Number(process.env.GATEWAY_PORT) || 8080;
const GAME_PORT = Number(process.env.GAME_PORT) || 3004;
const CHAT_PORT = Number(process.env.CHAT_PORT) || 3003;
const PROJECT_DIR = __dirname;
/* ---- MIME types ---- */
const MIME = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.mjs': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2':'font/woff2',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.mp3': 'audio/mpeg',
'.ogg': 'audio/ogg',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.txt': 'text/plain; charset=utf-8',
'.map': 'application/json; charset=utf-8',
};
/* ---- HTTP proxy helper ---- */
function proxyHttp(targetPort, targetPath, req, res) {
const opts = {
hostname: '127.0.0.1',
port: targetPort,
path: targetPath,
method: req.method,
headers: Object.assign({}, req.headers, { host: '127.0.0.1:' + targetPort }),
};
const proxy = http.request(opts, (upstream) => {
res.writeHead(upstream.statusCode, upstream.headers);
upstream.pipe(res, { end: true });
});
proxy.on('error', () => {
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Backend not running on port ' + targetPort);
});
req.pipe(proxy, { end: true });
}
/* ---- Static file server ---- */
function serveStatic(urlPath, res) {
let rel = decodeURIComponent(urlPath);
if (!rel || rel === '/') rel = '/index.html';
if (rel.includes('..')) {
res.writeHead(403);
return res.end('Forbidden');
}
const fsPath = path.join(PROJECT_DIR, rel);
try {
if (fs.statSync(fsPath).isDirectory()) {
const idx = path.join(fsPath, 'index.html');
if (fs.existsSync(idx)) return serveFile(idx, res);
}
} catch (_) { /* not a dir */ }
serveFile(fsPath, res);
}
function serveFile(fsPath, res) {
fs.readFile(fsPath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('404 Not Found: ' + fsPath);
}
const ext = path.extname(fsPath).toLowerCase();
res.writeHead(200, {
'Content-Type': MIME[ext] || 'application/octet-stream',
'Cache-Control': 'no-cache',
});
res.end(data);
});
}
/* ---- HTTP request handler ---- */
const server = http.createServer((req, res) => {
const urlNoQs = (req.url || '/').split('?')[0];
// ALL /Game/* → Node Game server (3004)
if (urlNoQs.startsWith('/Game/') || urlNoQs === '/Game') {
return proxyHttp(GAME_PORT, req.url, req, res);
}
// ALL /realtimechat/* → Node Chat server (3003)
if (urlNoQs.startsWith('/realtimechat/') || urlNoQs === '/realtimechat') {
return proxyHttp(CHAT_PORT, req.url, req, res);
}
// Gateway ไม่รัน PHP — เตือนชัดเจนแทนที่จะส่งไฟล์ดิบ
if (urlNoQs.toLowerCase().endsWith('.php')) {
res.writeHead(501, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end(
'PHP ไม่ถูกประมวลผลใน gateway นี้\n' +
'หากต้องการใช้ /Admin/ หรือ OAuth → เปิด WAMP/Apache แยก\n' +
'URL: ' + urlNoQs
);
}
// ไฟล์ที่เหลือ (Login, Main-Lobby, Main-Menu, Create Room, Loading, Quiz-Battle, ...)
serveStatic(urlNoQs, res);
});
/* ---- WebSocket upgrade handler (สำหรับ socket.io) ---- */
server.on('upgrade', (req, socket, head) => {
const url = req.url || '';
let targetPort = null;
if (url.startsWith('/Game/')) targetPort = GAME_PORT;
else if (url.startsWith('/realtimechat/')) targetPort = CHAT_PORT;
if (!targetPort) {
socket.destroy();
return;
}
const proxy = net.connect(targetPort, '127.0.0.1', () => {
const reqLine = req.method + ' ' + url + ' HTTP/' + req.httpVersion + '\r\n';
const headers = Object.assign({}, req.headers, { host: '127.0.0.1:' + targetPort });
let headerStr = '';
for (const [k, v] of Object.entries(headers)) {
headerStr += k + ': ' + v + '\r\n';
}
proxy.write(reqLine + headerStr + '\r\n');
if (head && head.length) proxy.write(head);
proxy.pipe(socket, { end: true });
socket.pipe(proxy, { end: true });
});
proxy.on('error', () => socket.destroy());
socket.on('error', () => proxy.destroy());
});
server.listen(GATEWAY_PORT, () => {
console.log('');
console.log(' ==========================================');
console.log(' game-justic2 Gateway');
console.log(' http://localhost:' + GATEWAY_PORT + '/');
console.log(' ==========================================');
console.log(' Game (HTTP+WS) -> http://127.0.0.1:' + GAME_PORT);
console.log(' Chat (HTTP+WS) -> http://127.0.0.1:' + CHAT_PORT);
console.log(' ==========================================');
console.log('');
});