简体   繁体   English

如何实现使用socket.io的时间

[英]How to implement time to live with socket.io

I believe I have surfed the web enough but still cant get any resources on the topic. 我相信我已经在网上冲浪了足够的时间,但是仍然无法获得有关该主题的任何资源。 How can I implement the 'time-to-live' function with Socket.io ? 如何使用Socket.io实现“生存时间”功能?

I am using Node.js with express . 我将Node.jsexpress一起使用 The above mentioned time-to-live function is intended to work as described below: 以上提到time-to-live功能旨在按以下说明工作:

If I specify timeToLive = 10; 如果我指定timeToLive = 10; secs, clients that connect in less than 10 sec after the message is emitted should still get the message. 几秒钟后,发出消息后不到10秒钟内连接的客户端仍应收到该消息。 This function is available on some of the cloud messaging libraries like GCM . 某些云消息传递库(例如GCM )可以使用此功能。

Any online resource will appreciated. 任何在线资源将不胜感激。

There is no such functionality in socket.io . socket.io中没有此类功能。 You will have to implement it yourself. 您将必须自己实施。 Consider using an array of objects that holds messages and Date.now() of that message and loop it when a user connects. 考虑使用对象数组来保存消息和该消息的 Date.now() ,并在用户连接时将其循环。 Delete any messages that are expired and emit the ones that are still valid . 删除所有过期的消息并发出仍然有效的消息 Minimum code could be this but due to heavy use of splice it could be slow. 最少的代码可能是这样,但是由于大量使用接头,它可能会很慢。

var messages = [];
var TTL = 10;


io.on('connection', function (socket) {
   for(i = 0; i < messages.length; i++)
       if(messages[i].time + TTL < Date.now())
           messages.splice(i, 1);
   socket.emit('data', messages);
});

Consider using redis or any other high performance database to also synchronize between multiple servers if you require that: 如果需要,请考虑使用redis或任何其他高性能数据库在多个服务器之间也进行同步:

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

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