-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (68 loc) · 2.47 KB
/
Copy pathserver.js
File metadata and controls
78 lines (68 loc) · 2.47 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
#!/usr/bin/env node
// server.js — Bridge Server 入口
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { ConnectionRegistry } = require('./lib/server/registry');
const { WebSocketHub } = require('./lib/server/ws-hub');
const { Router } = require('./lib/server/router');
// 加载配置
const configPath = path.join(__dirname, 'config.json');
let config;
try {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch (e) {
console.error('[server] 未找到 config.json,请先复制 config.example.json 并填写配置:');
console.error('[server] cp config.example.json config.json');
process.exit(1);
}
// 自动生成 token(如果未配置)
if (!config.bridge.token) {
config.bridge.token = crypto.randomBytes(24).toString('hex');
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
console.error('[server] 已自动生成 access token 并写入 config.json');
}
// 初始化组件
const registry = new ConnectionRegistry();
const wsHub = new WebSocketHub({
registry,
port: config.bridge.port,
host: config.bridge.host,
heartbeatInterval: config.bridge.heartbeatInterval,
heartbeatTimeout: config.bridge.heartbeatTimeout,
heartbeatMaxFailures: config.bridge.heartbeatMaxFailures,
maxPayload: config.bridge.maxBodySize,
});
const router = new Router({
registry,
wsHub,
requestTimeout: config.bridge.requestTimeout || 30000,
token: config.bridge.token,
maxBodySize: config.bridge.maxBodySize,
});
// 创建 HTTP Server
const httpServer = http.createServer((req, res) => {
router.handle(req, res);
});
// 将 WebSocket attach 到 HTTP Server(共用端口)
wsHub.attach(httpServer);
// 启动监听
const bridgeHost = config.bridge.host;
const bridgePort = config.bridge.port;
httpServer.listen(bridgePort, bridgeHost, () => {
console.error(`[server] Bridge Server ready — http://${bridgeHost}:${bridgePort}`);
console.error(`[server] Health: http://${bridgeHost}:${bridgePort}/api/health`);
console.error(`[server] Status: http://${bridgeHost}:${bridgePort}/api/status`);
console.error(`[server] WebSocket: ws://${bridgeHost}:${bridgePort}/ws`);
console.error('[server] Waiting for Tampermonkey scripts to connect...');
});
// 优雅退出
async function shutdown() {
console.error('\n[server] Shutting down...');
httpServer.close();
await wsHub.stop();
process.exit(0);
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);