我正在尝试确定用户何时关闭其连接。问题是,当我尝试使用this._session.socket.on("close",...)
时,它也会在用户刷新时进行注册。
这是我的代码:
Meteor.publish("friends", function () {
var id = this._session.userId;
this._session.socket.on("close", Meteor.bindEnvironment(function()
{
// This logs when the user disconnects OR refreshes
console.log(id);
}, function(e){console.log(e)}))
return Meteor.users.find({...});
});
如何区分刷新和真正的断开连接?
编辑:如果可能,我真的想避免使用'保持活动'功能。
答案 0 :(得分:1)
好的,这有点哈哈,但我不确定是否有更好的解决方案。这需要mizzao:user-status包。我解决这个问题的方法是在"关闭"内部调用流星方法。以5秒为间隔开始轮询数据库的功能,并检查用户的状态是否在线。经过一段时间(我说65秒),如果用户上线,我知道这是一次刷新。
无论如何,上面的内容有点令人困惑,所以这里是代码:
//server
Meteor.publish("some_collection", function(){
var id = this._session.userId;
this._session.socket.on("close", Meteor.bindEnvironment(function(){
Meteor.call("connectionTest", id);
}, function(e){console.log(e)}));
return Meteor.users.find({..});
});
//Meteor method
Meteor.methods({
connectionTest: function(userId){
this.unblock();
var i = 0;
var stop = false;
var id = Meteor.setInterval(function(){
var online = Meteor.users.findOne(userId).status.online;
if(!online){
console.log("offline");
}
else{
stop = true;
console.log("still online");
}
i++;
if(stop || i > 12){
if(online){
//do something
}
else{
// do something else
}
Meteor.clearInterval(id);
}
}, 5000);
}
});