Firebase - 统计在线用户

时间:2013-04-12 23:04:26

标签: firebase

我尝试使用presence进行游戏,以显示元素中的总连接用户数。我无法弄清楚在哪里看。我做了类似的事情:

var dataUlist = new Firebase('https://<url>.firebaseio.com/.info/connected');
dataUlist.on('value', function(snap) {
    console.log(snap);
});

试着看看我是否能找到有用的东西,但是(我有点期待)我无法理解数据。

有没有办法帮助我做什么?获取已连接用户的总数,例如。在控制台或元素中回显它?或者也许如何获取授权用户列表和未授权用户?

编辑:我想用英语拼写我的拼写,我不是美国人。谢谢。

2 个答案:

答案 0 :(得分:30)

.info/connected仅返回有关当前客户端是否已连接的信息。为了维持在线计数,您需要通过存储每个用户的状态信息并使用setOnDisconnect()来创建计数器。例如:

var listRef = new Firebase("https://<url>.firebaseio.com/presence/");
var userRef = listRef.push();

// Add ourselves to presence list when online.
var presenceRef = new Firebase("https://<url>.firebaseio.com/.info/connected");
presenceRef.on("value", function(snap) {
  if (snap.val()) {
    // Remove ourselves when we disconnect.
    userRef.onDisconnect().remove();

    userRef.set(true);
  }
});

// Number of online users is the number of objects in the presence list.
listRef.on("value", function(snap) {
  console.log("# of online users = " + snap.numChildren());
});    

答案 1 :(得分:0)

以下是Anant格式化为Android的代码

public void getDbCount() {

    Firebase listRef = new Firebase("https://<your-firebase-database>.firebaseio.com/presence/");
    final Firebase userRef = listRef.push();

    // Add ourselves to presence list when online.
    Firebase presenceRef = new Firebase("https://<your-firebase-database>.firebaseio.com/.info/connected");

    ValueEventListener myPresence = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            // Remove ourselves when we disconnect.
            userRef.onDisconnect().removeValue();
            userRef.setValue(true);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Log.e("DBCount", "The read failed: " + firebaseError.getMessage());
        }
    };

    presenceRef.addValueEventListener(myPresence);

    // Number of online users is the number of objects in the presence list.
    ValueEventListener myList = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            // Remove ourselves when we disconnect.
            Log.i("DBCount", "# of online users = " + String.valueOf(snapshot.getChildrenCount()));
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Log.e("DBCount", "The read failed: " + firebaseError.getMessage());
        }
    };

    listRef.addValueEventListener(myList);
}