|
|
@ -89,7 +89,17 @@ function setupTcpProxy(conf) { |
|
|
|
|
|
|
|
|
// console.log('缓冲区剩余数据:', tcpDataBuffer.length, '字节');
|
|
|
// console.log('缓冲区剩余数据:', tcpDataBuffer.length, '字节');
|
|
|
}); |
|
|
}); |
|
|
|
|
|
function compactJson(str) { |
|
|
|
|
|
try { |
|
|
|
|
|
// 如果是 JSON 字符串,解析后再 stringify(无换行/缩进)
|
|
|
|
|
|
if (typeof str === 'string') return JSON.stringify(JSON.parse(str)); |
|
|
|
|
|
// 如果是对象/Buffer等,统一转成无格式 JSON 字符串
|
|
|
|
|
|
return JSON.stringify(str); |
|
|
|
|
|
} catch { |
|
|
|
|
|
// 非 JSON 的情况,去掉所有换行,避免触发 \n\n 分隔
|
|
|
|
|
|
return String(str).replace(/\r?\n/g, ' '); |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
// WebSocket接收数据,转发到TCP
|
|
|
// WebSocket接收数据,转发到TCP
|
|
|
ws.on('message', (data) => { |
|
|
ws.on('message', (data) => { |
|
|
// 处理可能的Buffer数据,转换为字符串
|
|
|
// 处理可能的Buffer数据,转换为字符串
|
|
|
@ -97,29 +107,24 @@ function setupTcpProxy(conf) { |
|
|
|
|
|
|
|
|
if (Buffer.isBuffer(data)) { |
|
|
if (Buffer.isBuffer(data)) { |
|
|
messageStr = data.toString('utf8'); |
|
|
messageStr = data.toString('utf8'); |
|
|
// console.log('WebSocket数据(Buffer转字符串):', messageStr);
|
|
|
|
|
|
} else if (typeof data === 'string') { |
|
|
} else if (typeof data === 'string') { |
|
|
messageStr = data; |
|
|
messageStr = data; |
|
|
// console.log('WebSocket数据(字符串):', messageStr);
|
|
|
|
|
|
} else { |
|
|
} else { |
|
|
// console.warn('收到未知类型数据,已忽略:', typeof data);
|
|
|
|
|
|
return; |
|
|
return; |
|
|
} |
|
|
} |
|
|
|
|
|
messageStr = compactJson(messageStr); |
|
|
// 转发字符串数据到TCP服务器
|
|
|
// 转发字符串数据到TCP服务器
|
|
|
if (tcpClient.writable) { |
|
|
if (tcpClient.writable) { |
|
|
console.log('发送数据到TCP服务器:', messageStr); |
|
|
console.log('发送数据到TCP服务器:', messageStr); |
|
|
|
|
|
|
|
|
// 检查数据大小
|
|
|
// 检查数据大小
|
|
|
const dataSize = Buffer.byteLength(messageStr, 'utf8'); |
|
|
// const dataSize = Buffer.byteLength(messageStr, 'utf8');
|
|
|
// console.log(`数据大小: ${dataSize} bytes`);
|
|
|
// console.log(`数据大小: ${dataSize} bytes`);
|
|
|
|
|
|
|
|
|
// 直接发送完整数据
|
|
|
// 直接发送完整数据
|
|
|
tcpClient.write(messageStr + '\n\n', (err) => { |
|
|
tcpClient.write(messageStr + '\n\n', (err) => { |
|
|
if (err) { |
|
|
if (err) { |
|
|
console.error(`[${new Date().toLocaleString()}] TCP发送数据错误:`, err); |
|
|
console.error(`[${new Date().toLocaleString()}] TCP发送数据错误:`, err); |
|
|
} else { |
|
|
|
|
|
// console.log('数据已发送到TCP服务器');
|
|
|
|
|
|
} |
|
|
} |
|
|
}); |
|
|
}); |
|
|
} else { |
|
|
} else { |
|
|
|