'use strict'; const net = require('node:net'); const LOCAL_PORT = 1935; const REMOTE_PORT = 1936; const REMOTE_ADDR = '127.0.0.1'; /** * 头长度(Byte) */ const HEAD_LEN = 4; /** * 标识长度(Byte) */ const IDENTIFIER_LEN = 2; /** * 目标媒体服务器标识 * 10:9999 -> 16:270f * 支持2字节对应最大十进制32767 */ const MEDIA_SERVER_IDENTIFIER = 9999; const proxy = net.createServer(function (socket) { const targetSocket = net.createConnection({ host: REMOTE_ADDR, port: REMOTE_PORT, }, function () { console.log('Proxy connected to target server'); }); socket.on('data', function (data) { // 写入标识 const identifierBuf = Buffer.alloc(IDENTIFIER_LEN); identifierBuf.writeInt16BE(MEDIA_SERVER_IDENTIFIER, 0); // 写入包头 const headBuf = Buffer.alloc(HEAD_LEN); headBuf.writeUInt32BE(data.byteLength + IDENTIFIER_LEN, 0); // 发送包头 targetSocket.write(headBuf); // 发送标识 targetSocket.write(identifierBuf); // 发送包内容 targetSocket.write(data); // console.log(data.toString('hex')); }); socket.on('close', function () { targetSocket.end(); console.log('client disconnected'); }); socket.on('error', function (error) { console.log(`error:客户端异常断开: ${error}`); }); targetSocket.on('data', function (chunk) { socket.write(chunk); }); targetSocket.on('close', function () { socket.end(); }); }); proxy.on('error', function (err) { throw err; }); proxy.listen(LOCAL_PORT, function () { console.log('Zone1 proxy listening on ' + LOCAL_PORT); });