| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- const net = require('node:net');
- const LOCAL_PORT = 1936;
- const REMOTE_PORT = 1935;
- const REMOTE_ADDR = '39.101.185.102';
- /**
- * 包头是4字节无符号整数,表示数据包长度
- */
- const HEADER_LENGTH = 4;
- const routeTable = {
- '01020304': { host: '39.101.185.102', port: 1935 },
- }
- function bootstrap() {
- const proxy = net.createServer();
- proxy.on('connection', (clientSocket) => {
- console.log('Client connected');
- let num = 0;
- let buf = Buffer.alloc(0);
- let framelen = 0;
- // 创建一个新的连接到目标服务器
- const targetSocket = net.createConnection({
- host: REMOTE_ADDR,
- port: REMOTE_PORT,
- }, () => {
- console.log('Proxy connected to target server');
- });
- // 将接收到的数据转发到目标服务器
- clientSocket.on('data', chunk => {
- console.log('接收原始报文:', chunk.toString('hex'));
- buf = Buffer.concat([buf, chunk]);
- console.log('buffer length', buf.length);
- let origin;
- const chunklen = chunk.length;
- if (chunklen < HEADER_LENGTH) return;
- framelen = framelen || buf.readUInt32BE(0);
- if (chunklen - HEADER_LENGTH === framelen) {
- origin = buf.subarray(HEADER_LENGTH, chunklen);
- buf = Buffer.alloc(0);
- framelen = 0;
- } else if (chunklen - HEADER_LENGTH > framelen) {
- origin = buf.subarray(HEADER_LENGTH, chunklen);
- buf = buf.subarray(chunklen);
- if (buf.length >= HEADER_LENGTH) {
- framelen = buf.readUInt32BE(0);
- } else {
- framelen = 0;
- }
- }
- console.log('数据帧长度:', framelen);
- if (origin) {
- num += 1;
- targetSocket.write(origin);
- console.log('第'+num+'段报文', origin.toString('hex'));
- }
- });
- // 将目标服务器的响应数据转发回客户端
- targetSocket.on('data', chunk => {
- clientSocket.write(chunk);
- });
- // 处理代理与目标服务器的关闭事件
- clientSocket.on('close', () => {
- targetSocket.end();
- });
- targetSocket.on('close', () => {
- clientSocket.end();
- });
- });
- // 监听本地端口
- proxy.listen(LOCAL_PORT, () => {
- console.log('Zone2 proxy server is listening on port ' + LOCAL_PORT);
- });
- }
- bootstrap();
|