node.js - 如何在 Node.js 中关闭 tls 套接字连接?

标签 node.js sockets ssl

我在下面编写了 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 时触发 enderror 事件。

最佳答案

我修复了如下的套接字挂起问题。

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/

相关文章:

node.js - 包含 JSON 文件作为 Webpack 输出,但不属于 bundle.js

node.js - Node 以错误退出状态结束 3221225786

javascript - 使用 superagent-cache 缓存不同参数的 HTTP 响应

c# - 已将证书导入根权限,但仍无法建立信任关系

c# - 使用 HttpClientCertificate 与 X509Certificate2 检查证书有效性

mysql - AWS Lambda + Nodejs + MySQL

jquery - Socket.io - 无法从客户端向服务器端发送消息

python - Golang net.Listen 绑定(bind)到已在使用的端口

c - strtol() 错误地返回 0

java - SSLServerSocket 和证书设置