19

我尝试使用presence它来显示元素中的连接用户总数。我真的不知道在哪里看。我做了类似的事情:

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

尝试看看我是否可以在那里找到任何有用的东西,但是(我有点期待)我无法理解这些数据。

有什么方法可以帮我做我所追求的吗?获取连接用户的总数,例如。在控制台或元素中回显它?或者也许如何获取授权用户和非授权用户的列表?

编辑:我想保持我的英文拼写,我不是美国人。谢谢你。

4

2 回答 2

33

.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());
});    
于 2013-04-12T23:47:23.083 回答
1

这是为 Android 格式化的 Anant 代码

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);
}
于 2016-04-08T02:45:04.070 回答