【问题标题】:How to close tls socket connection in Node.js?如何在 Node.js 中关闭 tls 套接字连接?
【发布时间】:2018-11-22 03:07:17
【问题描述】:

我在 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 事件。

【问题讨论】:

    标签: node.js sockets ssl


    【解决方案1】:

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

    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 秒后,它会引发超时,之后代码将执行错误块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多