node.js - handling TCP socket error ECONNREFUSED

后端 未结 2 1688
醉酒成梦
醉酒成梦 2021-02-02 10:39

I\'m using node.js with socket.io to give my web page access to character data served by a TCP socket. I\'m quite new to node.js.

User ---->

相关标签:
2条回答
  • 2021-02-02 11:03

    The only way I found to fix this is wrapping the net stuff in a domain:

    const domain = require('domain');
    const net = require('net');
    
    const d = domain.create();
    
    d.on('error', (domainErr) => {
        console.log(domainErr.message);
    });
    
    d.run(() => {
        const client = net.createConnection(options, () => {
    
            client.on('error', (err) => {
                throw err;
            });
            client.write(...);
            client.on('data', (data) => {
                ...
            });
        });
    });
    

    The domain error captures error conditions which arise before the net client has been created, such as an invalid host.

    See also: https://nodejs.org/api/domain.html

    0 讨论(0)
  • 2021-02-02 11:14

    I ran the following code:

    var net = require('net');
    
    var client = net.connect(5558, 'localhost', function() {
      console.log("bla");
    });
    client.on('error', function(ex) {
      console.log("handled error");
      console.log(ex);
    });
    

    As I do not have 5558 open, the output was:

    $ node test.js
    handled error
    { [Error: connect ECONNREFUSED]
      code: 'ECONNREFUSED',
      errno: 'ECONNREFUSED',
      syscall: 'connect' }
    

    This proves that the error gets handled just fine... suggesting that the error is happening else-where.

    As discussed in another answer, the problem is actually this line:

    webSocket.emit('error', error);
    

    The 'error' event is special and needs to be handled somewhere (if it isn't, the process ends).

    Simply renaming the event to 'problem' or 'warning' results in the whole error object being transmitted back through the socket.io socket up to the web page:

    webSocket.emit('warning', error);
    
    0 讨论(0)
提交回复
热议问题