node.js - handling TCP socket error ECONNREFUSED

后端 未结 2 1689
醉酒成梦
醉酒成梦 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: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);
    

提交回复
热议问题