You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
202 lines
5.9 KiB
202 lines
5.9 KiB
const net = require('net');
|
|
const WebSocket = require('ws');
|
|
|
|
// TCP代理配置
|
|
let TCP_HOST = '127.0.0.1';
|
|
const TCP_PORT = 2230;
|
|
|
|
function setupTcpProxy(conf) {
|
|
if (conf && conf.flag === 'localdev') {
|
|
TCP_HOST = '10.8.30.179'
|
|
}
|
|
console.log(`TCP代理目标地址: ${TCP_HOST}:${TCP_PORT}`);
|
|
|
|
const wsPort = (conf && conf.port) ? Number(conf.port) + 1 : 5001;
|
|
|
|
const wss = new WebSocket.Server({
|
|
port: wsPort,
|
|
host: '0.0.0.0',
|
|
path: '/tcp-proxy'
|
|
});
|
|
|
|
wss.on('connection', (ws, request) => {
|
|
console.log(`WebSocket连接建立,来自: ${request.socket.remoteAddress}`);
|
|
|
|
const tcpClient = new net.Socket();
|
|
let tcpDataBuffer = '';
|
|
let tcpConnected = false;
|
|
let connectionTimeout = null;
|
|
|
|
// 设置连接超时
|
|
connectionTimeout = setTimeout(() => {
|
|
if (!tcpConnected) {
|
|
console.error('TCP连接超时');
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
ws.close(1011, 'TCP连接超时');
|
|
}
|
|
tcpClient.destroy();
|
|
}
|
|
}, 5000); // 5秒超时
|
|
|
|
// TCP连接成功
|
|
tcpClient.connect(process.env.TCP_PORT || TCP_PORT, process.env.TCP_HOST || TCP_HOST, () => {
|
|
console.log(`TCP连接已建立到 ${TCP_HOST}:${TCP_PORT}`);
|
|
tcpConnected = true;
|
|
|
|
// 清除超时定时器
|
|
if (connectionTimeout) {
|
|
clearTimeout(connectionTimeout);
|
|
connectionTimeout = null;
|
|
}
|
|
|
|
// 向WebSocket客户端发送就绪信号
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
const readySignal = JSON.stringify({
|
|
_from: 'proxy',
|
|
cmd: 'ready',
|
|
values: {
|
|
message: 'TCP connection established',
|
|
timestamp: Date.now()
|
|
}
|
|
});
|
|
ws.send(readySignal);
|
|
}
|
|
});
|
|
|
|
// TCP接收数据,转发到WebSocket
|
|
tcpClient.on('data', (data) => {
|
|
try {
|
|
const textData = data.toString('utf8');
|
|
tcpDataBuffer += textData;
|
|
|
|
let endIndex;
|
|
while ((endIndex = tcpDataBuffer.indexOf('\n\n')) !== -1) {
|
|
const completeMessage = tcpDataBuffer.substring(0, endIndex);
|
|
tcpDataBuffer = tcpDataBuffer.substring(endIndex + 2);
|
|
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
ws.send(completeMessage, (err) => {
|
|
if (err) {
|
|
console.error(`WebSocket发送数据错误:`, err);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
} catch (e) {
|
|
console.error('TCP数据处理错误:', e);
|
|
}
|
|
});
|
|
|
|
function compactJson(str) {
|
|
try {
|
|
if (typeof str === 'string') {
|
|
return JSON.stringify(JSON.parse(str));
|
|
}
|
|
return JSON.stringify(str);
|
|
} catch {
|
|
return String(str).replace(/\r?\n/g, ' ');
|
|
}
|
|
}
|
|
|
|
// WebSocket接收数据,转发到TCP
|
|
ws.on('message', (data) => {
|
|
try {
|
|
let messageStr;
|
|
if (Buffer.isBuffer(data)) {
|
|
messageStr = data.toString('utf8');
|
|
} else if (typeof data === 'string') {
|
|
messageStr = data;
|
|
} else {
|
|
return;
|
|
}
|
|
|
|
messageStr = compactJson(messageStr);
|
|
|
|
if (tcpClient.writable && tcpConnected) {
|
|
console.log('发送数据到TCP服务器:', messageStr);
|
|
tcpClient.write(messageStr + '\n\n', (err) => {
|
|
if (err) {
|
|
console.error('TCP发送数据错误:', err);
|
|
}
|
|
});
|
|
} else {
|
|
console.warn('TCP连接不可用,无法发送数据');
|
|
}
|
|
} catch (e) {
|
|
console.error('WebSocket消息处理错误:', e);
|
|
}
|
|
});
|
|
|
|
// TCP连接错误处理
|
|
tcpClient.on('error', (err) => {
|
|
console.error('TCP连接错误:', err);
|
|
tcpConnected = false;
|
|
tcpDataBuffer = '';
|
|
|
|
// 清除超时定时器
|
|
if (connectionTimeout) {
|
|
clearTimeout(connectionTimeout);
|
|
connectionTimeout = null;
|
|
}
|
|
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
ws.close(1011, `TCP连接错误: ${err.message}`);
|
|
}
|
|
});
|
|
|
|
// TCP连接关闭
|
|
tcpClient.on('close', () => {
|
|
console.log('TCP连接已关闭');
|
|
tcpConnected = false;
|
|
tcpDataBuffer = '';
|
|
|
|
if (connectionTimeout) {
|
|
clearTimeout(connectionTimeout);
|
|
connectionTimeout = null;
|
|
}
|
|
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
ws.close(1000, 'TCP连接关闭');
|
|
}
|
|
});
|
|
|
|
// WebSocket连接关闭
|
|
ws.on('close', (code, reason) => {
|
|
console.log(`WebSocket连接已关闭: ${code} - ${reason}`);
|
|
tcpDataBuffer = '';
|
|
|
|
if (connectionTimeout) {
|
|
clearTimeout(connectionTimeout);
|
|
connectionTimeout = null;
|
|
}
|
|
|
|
if (tcpClient && !tcpClient.destroyed) {
|
|
tcpClient.destroy();
|
|
}
|
|
});
|
|
|
|
// WebSocket错误处理
|
|
ws.on('error', (err) => {
|
|
console.error('WebSocket错误:', err);
|
|
if (tcpClient && !tcpClient.destroyed) {
|
|
tcpClient.destroy();
|
|
}
|
|
});
|
|
});
|
|
|
|
wss.on('listening', () => {
|
|
console.log(`TCP代理WebSocket服务器已启动在端口 ${wsPort},路径: /tcp-proxy`);
|
|
console.log(`本地连接地址: ws://localhost:${wsPort}/tcp-proxy`);
|
|
});
|
|
|
|
wss.on('error', (err) => {
|
|
console.error('WebSocket服务器错误:', err);
|
|
if (err.code === 'EADDRINUSE') {
|
|
console.error(`端口 ${wsPort} 已被占用,请检查是否有其他服务在使用该端口`);
|
|
}
|
|
});
|
|
|
|
return wss;
|
|
}
|
|
|
|
module.exports = { setupTcpProxy };
|
|
|