2012-11-24 34 views
10

我在Meteor編寫了一個數據敏感的應用程序,並試圖限制客戶端訪問儘可能多的信息。因此,我想實現服務器端計算登錄和匿名用戶數量的方法。如何跟蹤Meteor中服務器端的匿名用戶數量?

我嘗試了各種方法。第一次是在這個問題Server cleanup after a client disconnects,這表明鉤住概述:

this.session.socket.on("close") 

然而,當我做到了,並試圖改變一個集合,它拋出一個錯誤「流星代碼必須在光纖中運行」。我認爲這個問題是因爲一旦套接字關閉,光纖被殺死,因此訪問數據庫是不可能的。 OP指出這個"Meteor code must always run within a Fiber" when calling Collection.insert on server是一個可能的解決方案,但我不確定這是否是最好的方法,根據評論的答案。

我又試圖自動運行的變量:

Meteor.default_server.stream_server.all_sockets().length 

但自動運行似乎從來沒有被調用,所以我假設變量不是反應方面,我不知道如何成爲一個。

最後的想法是做一個存活風格的東西,但似乎完全違背流星理念的糧食,我想我只能將作爲一個絕對的最後手段使用。

我在this.session.socket上做了console.log的功能,唯一可能的其他功能是.on("data"),但是在套接字關閉時不會調用它。

我在這裏有點茫然的,所以任何幫助將是巨大的, 感謝。

回答

8

爲了完整起見,最好結合上面的兩個答案。換句話說,執行以下操作:

這很可能是流星實現這個規範的方式。我已經創建了這個作爲一個智能包,你可以用隕石安裝:https://github.com/mizzao/meteor-user-status

+0

不能感謝你足夠:) – Pawan

+0

雖然這是非常酷,但文檔明確表示它不跟蹤匿名用戶,所以它不能真正回答原來的問題。 – cazgp

+1

@cazgp由於我寫了這篇文章,我已經更新了軟件包來跟蹤匿名用戶。很明顯,我們無法跟蹤'Meteor.users'中的匿名用戶,但他們的連接都被跟蹤。 –

2

結帳GitHub的項目howmanypeoplearelooking

流星應用測試顯示有多少用戶在線現在。

+0

這是一個惡作劇。我已經下載了代碼('Dumbs = new Meteor.Collection(「dumbs」);':)) – Matanya

+0

@Matanya:'Dumbs'只是一個幼稚的集合名稱,但[該應用程序工作](https:// github的.com/murilopolese/howmanypeoplearelooking /拉/ 2)。 –

3

由於Sorhus'末端,我設法解決這個問題。他的回答包含了一個我很想避免的心跳。但是,它包含了使用流星的「綁定環境」的技巧。這允許訪問集合,否則該集合將不可訪問。

Meteor.publish("whatever", function() { 
    userId = this.userId; 
    if(userId) Stats.update({}, {$addToSet: {users: userId}}); 
    else Stats.update({}, {$inc: {users_anon: 1}}); 

    // This is required, because otherwise each time the publish function is called, 
    // the events re-bind and the counts will start becoming ridiculous as the functions 
    // are called multiple times! 
    if(this.session.socket._events.data.length === 1) { 

    this.session.socket.on("data", Meteor.bindEnvironment(function(data) { 
     var method = JSON.parse(data).method; 

     // If a user is logging in, dec anon. Don't need to add user to set, 
     // because when a user logs in, they are re-subscribed to the collection, 
     // so the publish function will be called again. 
     // Similarly, if they logout, they re-subscribe, and so the anon count 
     // will be handled when the publish function is called again - need only 
     // to take out the user ID from the users array. 
     if(method === 'login') 
     Stats.update({}, {$inc: {users_anon: -1}}); 

     // If a user is logging out, remove from set 
     else if(method === 'logout') 
     Stats.update({}, {$pull: {users: userId}}); 

    }, function(e) { 
     console.log(e); 
    })); 

    this.session.socket.on("close", Meteor.bindEnvironment(function() { 
     if(userId === null || userId === undefined) 
     Stats.update({}, {$inc: {users_anon: -1}}); 
     else 
     Stats.update({}, {$pull: {users: userId}}); 
    }, function(e) { 
     console.log("close error", e); 
    })); 
    } 
} 
相關問題