Server cleanup after a client disconnects

后端 未结 5 1571
花落未央
花落未央 2020-12-01 07:55

Is there a way to detect when a client disconnects from a meteor server, either by refreshing or navigating away from the page, so that the server can attempt some cleanup?<

5条回答
  •  孤城傲影
    2020-12-01 08:35

    One technique is to implement a "keepalive" method that each client regularly calls. This assumes you've got a user_id held in each client's Session.

    // server code: heartbeat method
    Meteor.methods({
      keepalive: function (user_id) {
        if (!Connections.findOne(user_id))
          Connections.insert({user_id: user_id});
    
        Connections.update(user_id, {$set: {last_seen: (new Date()).getTime()}});
      }
    });
    
    // server code: clean up dead clients after 60 seconds
    Meteor.setInterval(function () {
      var now = (new Date()).getTime();
      Connections.find({last_seen: {$lt: (now - 60 * 1000)}}).forEach(function (user) {
        // do something here for each idle user
      });
    });
    
    // client code: ping heartbeat every 5 seconds
    Meteor.setInterval(function () {
      Meteor.call('keepalive', Session.get('user_id'));
    }, 5000);
    

提交回复
热议问题