客户端断开连接后的服务器清理
Server cleanup after a client disconnects
有没有办法通过刷新或离开页面来检测客户端何时与 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!');
}
});
相关文章:
- 使用JSP从服务器检索和显示图像
- 如何使用skip参数使用angular ui引导进行服务器端分页
- 客户端服务器REST API captcha实现
- 服务器上的Meteor客户端断开连接事件
- 套接字发生了什么's在'断开连接'事件(服务器端)
- SSE(服务器发送的事件)断开连接
- 客户端可以知道Node.js服务器已经断开了他的连接
- Websocket:服务器断开连接与页面导航
- socket.io 服务器在注册客户端断开连接时非常延迟
- Pusher.com - 当有人连接/断开连接时收到通知服务器端
- 断开连接的客户端在具有 websocket 的 Openfire 服务器上保持联机状态
- 客户端断开连接后的服务器清理
- Node.js聊天服务器,当另一个用户发送数据时,客户端断开连接
- Strophe.js客户端连接到服务器,断开连接/超时
- 在Backbone.js中,为什么有时会“断开连接”?从服务器
- 客户端是否有办法在套接字断开连接时发送服务器数据?
- 为什么客户端在服务器接收到emit后断开连接并重新连接
- 我如何断开套接字服务器端和客户端在套接字.io 1.0
- 当用户与node.js服务器断开连接时,删除数组项
- 我使用服务器发送事件(和Javascript/PHP)的连接会立即断开