如何关闭Node.js中的套接字连接?

时间:2018-06-12 16:28:43

标签: 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事件也被触发了。

如何确保代码不会在end上触发errortimeout事件。

1 个答案:

答案 0 :(得分:0)

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

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