Socket.IO server hangs up

2019-08-10 20:14发布

问题:

I am new to socket.io. So my socket.io server sometimws crashes giving this below error

timers.js:103
        if (!process.listeners('uncaughtException').length) throw e;
                                                                  ^
Error: socket hang up
    at createHangUpError (http.js:1360:15)
    at ServerResponse.OutgoingMessage._writeRaw (http.js:507:26)
    at ServerResponse.OutgoingMessage._send (http.js:476:15)
    at ServerResponse.OutgoingMessage.write (http.js:749:16)
    at XHRPolling.doWrite (E:\sitesroot\0\node_modules\socket.io\lib\transports\
xhr-polling.js:67:17)
    at XHRPolling.HTTPPolling.write (E:\sitesroot\0\node_modules\socket.io\lib\t
ransports\http-polling.js:132:8)
    at XHRPolling.Transport.packet (E:\sitesroot\0\node_modules\socket.io\lib\tr
ansport.js:515:15)
    at Object.<anonymous> (E:\sitesroot\0\node_modules\socket.io\lib\transports\
http-polling.js:79:12)
    at Timer.list.ontimeout (timers.js:101:19)

It doesnt show where or why the error is happening so pretty sure its nothing to do with the code i have written. Could be something with the transports? I dont have much knowledge on it. Any suggestions on how to stop it from crashing would be highly appreciated. Thanks

回答1:

The problem is as @miktam stated. To fix this you need to add an error listener to your code. Add this code to your application:

//Error handler
process.on('uncaughtException', function (exception) {
  // handle or ignore error
  console.log(exception);
});

When ever there is an error it will console.log it instead of crashing it. I had the exact same problem and this fixed it.



回答2:

Check this issue

Quoting Isaac Schlueter:

The good news is that you're no longer leaking memory. The bad news is that you do indeed need to add error listeners to your objects.

In most apps, you can usually treat ECONNRESET as roughly the same as a graceful close. Just make sure that you actually stop using that socket, since it's now closed. However, it's not a graceful close, since it's not in any sense "graceful". Prior to v0.8.20, node would happily buffer all writes to reset sockets, causing memory explosion death.