zone1.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const net = require('node:net');
  3. const LOCAL_PORT = 1935;
  4. const REMOTE_PORT = 1936;
  5. const REMOTE_ADDR = '127.0.0.1';
  6. /**
  7. * 头长度(Byte)
  8. */
  9. const HEAD_LEN = 4;
  10. /**
  11. * 标识长度(Byte)
  12. */
  13. const IDENTIFIER_LEN = 2;
  14. /**
  15. * 目标媒体服务器标识
  16. * 10:9999 -> 16:270f
  17. * 支持2字节对应最大十进制32767
  18. */
  19. const MEDIA_SERVER_IDENTIFIER = 9999;
  20. const proxy = net.createServer(function (socket) {
  21. const targetSocket = net.createConnection({
  22. host: REMOTE_ADDR,
  23. port: REMOTE_PORT,
  24. }, function () {
  25. console.log('Proxy connected to target server');
  26. });
  27. socket.on('data', function (data) {
  28. // 写入标识
  29. const identifierBuf = Buffer.alloc(IDENTIFIER_LEN);
  30. identifierBuf.writeInt16BE(MEDIA_SERVER_IDENTIFIER, 0);
  31. // 写入包头
  32. const headBuf = Buffer.alloc(HEAD_LEN);
  33. headBuf.writeUInt32BE(data.byteLength + IDENTIFIER_LEN, 0);
  34. // 发送包头
  35. targetSocket.write(headBuf);
  36. // 发送标识
  37. targetSocket.write(identifierBuf);
  38. // 发送包内容
  39. targetSocket.write(data);
  40. // console.log(data.toString('hex'));
  41. });
  42. socket.on('close', function () {
  43. targetSocket.end();
  44. console.log('client disconnected');
  45. });
  46. socket.on('error', function (error) {
  47. console.log(`error:客户端异常断开: ${error}`);
  48. });
  49. targetSocket.on('data', function (chunk) {
  50. socket.write(chunk);
  51. });
  52. targetSocket.on('close', function () {
  53. socket.end();
  54. });
  55. });
  56. proxy.on('error', function (err) {
  57. throw err;
  58. });
  59. proxy.listen(LOCAL_PORT, function () {
  60. console.log('Zone1 proxy listening on ' + LOCAL_PORT);
  61. });