Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long polling in node.js - how to 'timeout' the pending requests if no data is available?

I'm trying to implement an http long polling server in Node.js, and have no idea how to close/shutdown pending requests if a timeout is reached.

3 possible solutions come to my mind:

  1. Store the pendingRequest with a timestamp in a hash/object, then call setIntervall, so that every 1/2/x secs the pendingRequests are removed if the timestamp is too old.
  2. set a timeout on the socket connection

Both solutions don't seem very reasonable, so what would be the Node.js way to achieve something like this?

like image 558
helpermethod Avatar asked Mar 27 '12 18:03

helpermethod


1 Answers

Why don't those sound reasonable? In particular, setting a timeout on the socket seems to make sense to me, as:

  1. There is a built-in method for doing so
  2. An event is fired when the connection times out, allowing you to do any necessary cleanup (e.g. calling end/destroy on the socket)

I would probably go this route so that Node handles the timeout behind the scenes; however, if it makes sense for your app, I don't see any harm in keeping a timestamp and expiring connections manually.

You may be interested in these articles, each of which handles expiring connections differently:

  • Long polling in Node.js
  • How to write a Long Polling Event Push Server with node.js
like image 115
Michelle Tilley Avatar answered Sep 30 '22 04:09

Michelle Tilley