zone2.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const net = require('node:net');
  2. const LOCAL_PORT = 1936;
  3. const REMOTE_PORT = 1935;
  4. const REMOTE_ADDR = '39.101.185.102';
  5. /**
  6. * 包头是4字节无符号整数,表示数据包长度
  7. */
  8. const HEADER_LENGTH = 4;
  9. const routeTable = {
  10. '01020304': { host: '39.101.185.102', port: 1935 },
  11. }
  12. function bootstrap() {
  13. const proxy = net.createServer();
  14. proxy.on('connection', (clientSocket) => {
  15. console.log('Client connected');
  16. let num = 0;
  17. let buf = Buffer.alloc(0);
  18. let framelen = 0;
  19. // 创建一个新的连接到目标服务器
  20. const targetSocket = net.createConnection({
  21. host: REMOTE_ADDR,
  22. port: REMOTE_PORT,
  23. }, () => {
  24. console.log('Proxy connected to target server');
  25. });
  26. // 将接收到的数据转发到目标服务器
  27. clientSocket.on('data', chunk => {
  28. console.log('接收原始报文:', chunk.toString('hex'));
  29. buf = Buffer.concat([buf, chunk]);
  30. console.log('buffer length', buf.length);
  31. let origin;
  32. const chunklen = chunk.length;
  33. if (chunklen < HEADER_LENGTH) return;
  34. framelen = framelen || buf.readUInt32BE(0);
  35. if (chunklen - HEADER_LENGTH === framelen) {
  36. origin = buf.subarray(HEADER_LENGTH, chunklen);
  37. buf = Buffer.alloc(0);
  38. framelen = 0;
  39. } else if (chunklen - HEADER_LENGTH > framelen) {
  40. origin = buf.subarray(HEADER_LENGTH, chunklen);
  41. buf = buf.subarray(chunklen);
  42. if (buf.length >= HEADER_LENGTH) {
  43. framelen = buf.readUInt32BE(0);
  44. } else {
  45. framelen = 0;
  46. }
  47. }
  48. console.log('数据帧长度:', framelen);
  49. if (origin) {
  50. num += 1;
  51. targetSocket.write(origin);
  52. console.log('第'+num+'段报文', origin.toString('hex'));
  53. }
  54. });
  55. // 将目标服务器的响应数据转发回客户端
  56. targetSocket.on('data', chunk => {
  57. clientSocket.write(chunk);
  58. });
  59. // 处理代理与目标服务器的关闭事件
  60. clientSocket.on('close', () => {
  61. targetSocket.end();
  62. });
  63. targetSocket.on('close', () => {
  64. clientSocket.end();
  65. });
  66. });
  67. // 监听本地端口
  68. proxy.listen(LOCAL_PORT, () => {
  69. console.log('Zone2 proxy server is listening on port ' + LOCAL_PORT);
  70. });
  71. }
  72. bootstrap();