简体   繁体   English

在node.js中进行长时间轮询-如果没有可用数据,如何“暂停”挂起的请求?

[英]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. 我正在尝试在Node.js中实现一个HTTP长轮询服务器,并且不知道如何在超时时关闭/关闭挂起的请求。

3 possible solutions come to my mind: 我想到3种可能的解决方案:

  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. 将带有时间戳的未决请求存储在哈希/对象中,然后调用setIntervall,以便如果时间戳太旧,则每1/2 / x秒删除一次未决请求。
  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? 两种解决方案看起来都不是很合理,那么Node.js将如何实现这种目标呢?

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 (eg calling end / destroy on the socket) 连接超时时会触发一个事件,允许您进行任何必要的清除(例如,在套接字上调用end / destroy

I would probably go this route so that Node handles the timeout behind the scenes; 我可能会走这条路,以便Node处理后台的超时。 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: 您可能对这些文章感兴趣,每一篇文章对过期连接的处理方式都不同:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM