I built a streaming https server that polls a back-end service and writes the data to the http client if it is available. The code for a specific https request looks like this somehow:
// check for new stuff periodically
var timer = setInterval( function() {
var resp = getResponseObject();
response.write(resp + "\n\r");
}, 500);
// stop looping when the client disconnects
request.on('close', function() {
clearInterval(timer);
return;
});
When the client disconnects, the time-out gets cleared and the loop stops. But will this on-close event always be triggered? Also on a not-so-clean client disconnect? I worry about leaving loops behind for connections that are no longer in place.
Any idea if this is safe? Other approaches?
Thanks!
I don’t believe you need to worry about “unclean” disconnects — when the client machines are abruptly removed from the network, your server will eventually get either TCP
FINpackets or ICMP Destination Unreachable messages, which will trigger thecloseevent in your server and allow you to clean up.What is probably more resource intensive would be hundreds or thousands of clients sending and receiving data so slowly that you wind up running out of file descriptors for all the network sockets. A client that connects with ridiculously low MTU could force your application to dribble megabytes down a connection in 100-byte chunks for days or weeks.