-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
97 lines (79 loc) · 3.08 KB
/
main.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const net = require('net');
const mainServerHost = '113.150.233.75';
const mainServerPort = 15299;
const listenPorts = [13102, 13101, 14090, 14092, 13103, 13104, 14075]; // ここにリッスンしたいポートを追加
const minerSockets = {};
const mainServerSockets = {};
listenPorts.forEach(port => {
const receiverServer = net.createServer((socket) => {
const minerIdentifier = `${socket.remoteAddress}:${socket.remotePort}`;
minerSockets[minerIdentifier] = socket;
if (!mainServerSockets[minerIdentifier]) {
const mainServerSocket = new net.Socket();
mainServerSockets[minerIdentifier] = mainServerSocket;
mainServerSocket.connect(mainServerPort, mainServerHost, () => {
console.log('Connected to main server from port', port);
mainServerSockets[minerIdentifier] = mainServerSocket;
});
mainServerSocket.on('error', (err) => {
console.error(`Main server socket error: ${err}`);
delete mainServerSockets[minerIdentifier];
});
mainServerSocket.on('close', () => {
delete mainServerSockets[minerIdentifier];
if (minerSockets[minerIdentifier]) {
minerSockets[minerIdentifier].end();
}
});
let buffer = '';
mainServerSocket.on('data', (mainData) => {
buffer += mainData.toString('utf-8');
while (true) {
let braceCount = 0;
let endIndex = -1;
for (let i = 0; i < buffer.length; i++) {
if (buffer[i] === '{') braceCount++;
if (buffer[i] === '}') braceCount--;
if (braceCount === 0 && buffer[i] === '}') {
endIndex = i + 1;
break;
}
}
if (endIndex === -1) break; // 完全なJSONメッセージがまだ来ていない
const completeMessage = buffer.slice(0, endIndex);
buffer = buffer.slice(endIndex);
try {
const message = JSON.parse(completeMessage);
if (minerSockets[minerIdentifier]) {
minerSockets[minerIdentifier].write(message.data);
console.log(`Received data: ${message.data}`);
}
} catch (err) {
console.error(`Received data from main server is not valid JSON: ${completeMessage}`);
}
}
});
}
socket.on('data', (data) => {
const message = JSON.stringify({ minerIdentifier, data: data.toString('utf-8'), port: port });
if (mainServerSockets[minerIdentifier]) {
mainServerSockets[minerIdentifier].write(message);
}
});
socket.on('error', (err) => {
console.error(`Miner socket error: ${err}`);
});
socket.on('close', () => {
delete minerSockets[minerIdentifier];
if (mainServerSockets[minerIdentifier]) {
mainServerSockets[minerIdentifier].end();
}
});
});
receiverServer.listen(port, '0.0.0.0', () => {
console.log(`Receiver server is listening on port ${port}`);
});
receiverServer.on('error', (err) => {
console.error(`Receiver server error on port ${port}: ${err}`);
});
});