我在下面编写了 node.js 代码以打开与指定端口和主机的 TLS 连接。
var tls = require('tls');
(() => {
var output = {};
const client = tls.connect({
port: 5060,
host: "173.99.99.99",
}, () => {
console.log('connected to server!');
var cert = client.getPeerCertificate(true);
console.log("Connection success!!!");
});
client.setTimeout(1000);
client.on('timeout',()=>{
console.log("Requested timed out!");
client.end();
})
client.on('data', (data) => {
console.log("Data::",data);
client.end();
});
client.on('error', (err) => {
console.log('Error',err);
client.end();
});
client.on('end', (op) => {
client.destroy();
console.log('disconnected from server',op);
});
})();
并获得如下输出。
Requested timed out!
disconnected from server undefined
Error { Error: socket hang up
at TLSSocket.onConnectEnd (_tls_wrap.js:1083:19)
at Object.onceWrapper (events.js:272:13)
at TLSSocket.emit (events.js:185:15)
at endReadableNT (_stream_readable.js:1106:12)
at process._tickCallback (internal/process/next_tick.js:178:19)
code: 'ECONNRESET',
path: undefined,
host: '173.99.99.99',
port: 5060,
localAddress: undefined }
预期是,它首先执行 timeout
,然后执行 end
事件。但是 error
事件也触发了。
如何确保代码不会在 timeout
时触发 end
和 error
事件。
最佳答案
我修复了如下的套接字挂起问题。
let client = net.createConnection({
port: "Port",
host: "Hostname"
}, () => {
//Connection is Success. Do your stuff here!!
client.destroy();
});
client.setTimeout(5000);
client.on('timeout', (data) => {
// Connection timed-out.
client.destroy()
});
client.on('error', (err) => {
// Something went wrong while opening.
});
我正在销毁客户端,因为在打开连接 5 秒后,它会抛出超时,之后代码将执行错误 block 。
关于node.js - 如何在 Node.js 中关闭 tls 套接字连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50821888/