我的节点守护程序多次连接到相同 TLS服务器。我想保存TLS连接时间。
// repeat every 5 seconds
setInterval(() => {
const socket = tls.connect(443, 'test.com')
socket.on('connect', () => {
socket.write(someUniqueData)
})
}, 5000)
是否可以重用最后的TLS连接?
答案 0 :(得分:1)
您可以轻松地保存套接字,这是一个示例:
const tls = require('tls');
const someUniqueData = 'someUniqueData';
var savedSocket = null;
function getSocket() {
return new Promise((resolve, reject) => {
if (savedSocket) {
console.log('getSocket: Reusing saved socket..');
resolve(savedSocket);
return;
}
console.log('getSocket: Creating new socket..');
const socket = tls.connect(443, 'test.com');
socket.on('connect', () => {
console.log('Connected to host..');
savedSocket = socket;
resolve(savedSocket);
});
socket.on('error', (err) => {
console.log('Error connecting to host..');
reject(err);
});
});
}
async function connectAndSend() {
try {
let socket = await getSocket();
console.log('connectAndSend: Sending data..');
socket.write(someUniqueData)
} catch (err) {
console.error('connectAndSend: Error occurred: ', err);
}
}
// repeat every 5 seconds
setInterval(() => {
connectAndSend();
}, 5000)