客户端断开连接后的服务器清理

Server cleanup after a client disconnects

本文关键字:服务器 断开 连接 客户端      更新时间:2023-09-26

有没有办法通过刷新或离开页面来检测客户端何时与 meteor 服务器断开连接,以便服务器可以尝试一些清理?

一种技术是实现每个客户端定期调用的"keepalive"方法。 这假设您在每个客户的Session中都持有user_id

// 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);

我认为更好的方法是在发布函数中捕获套接字关闭事件。

Meteor.publish("your_collection", function() {
    this.session.socket.on("close", function() { /*do your thing*/});
}

更新:

较新版本的 meteor 使用如下_session:

this._session.socket.on("close", function() { /*do your thing*/});

我实现了一个 Meteor 智能包,它可以跟踪来自不同会话的所有连接会话并检测会话注销和断开连接事件,而无需昂贵的保持连接。

https://github.com/mizzao/meteor-user-status

要检测断开连接/注销事件,您只需执行以下操作:

UserStatus.on "connectionLogout", (info) ->
  console.log(info.userId + " with session " + info.connectionId + " logged out")

您也可以被动地使用它。看看吧!

编辑:用户状态v0.3.0现在也会跟踪用户空闲!

如果您使用的是身份验证,则可以在方法和发布函数中访问用户的ID,则可以在那里实现跟踪。 例如,您可以在用户切换房间时设置"最后看到":

Meteor.publish("messages", function(roomId) {
    // assuming ActiveConnections is where you're tracking user connection activity
    ActiveConnections.update({ userId: this.userId() }, {
        $set:{ lastSeen: new Date().getTime() }
    });
    return Messages.find({ roomId: roomId});
});

我正在使用 Iron Router 并在主控制器的 unload 事件上调用我的清理代码。当然,这不会捕获选项卡关闭的事件,但对于许多用例来说仍然感觉足够好

ApplicationController = RouteController.extend({
    layoutTemplate: 'root',
    data: {},
    fastRender: true,
    onBeforeAction: function () {
        this.next();
    },
    unload: function () {
        if(Meteor.userId())
            Meteor.call('CleanUpTheUsersTrash');
    },
    action: function () {
        console.log('this should be overridden by our actual controllers!');
    }
});