如何使用Firebase将警报消息发送给特殊的在线用户 [英] How to send an alert message to a special online user with firebase

查看:148
本文介绍了如何使用Firebase将警报消息发送给特殊的在线用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个FourConnect - 与JavaScript游戏。我想,所有在线用户都有一个列表。这个列表是我在firebase网站上的例子。现在我希望我可以选择一个在线用户,并向他们发送邀请与我一起玩。
所以我写了一个函数,所有用户期望我有一个额外的div。当我点击div这个特殊用户应该得到一个确认框说okey或取消。如果用户点击okey,应该开始播放。
我将保存用户的名字和ID。这已经起作用了。



我的问题是,我不知道如何将请求发送给其他用户。我尝试了很多,但总是确认框是在我的brwoser而不是在其他用户的浏览器。



我在firebase页面和谷歌寻找解决方案,但cann

我已经拥有的代码:

  var name = prompt(Your name?,Guest),
currentStatus =★online;

//获取对Firebase中状态数据的引用。
var userListRef = new Firebase(connectFour.CONFIG.firebaseUrl);

//通过push为我的用户生成一个新位置的引用。
var myUserRef = userListRef.push();
var gameId = myUserRef.name();
document.getElementById('labelGameId')。innerHTML = gameId;

beginGame({id:gameId,name:name,status:currentStatus});
//获取我自己的存在状态的参考。
var connectedRef =新的Firebase('http://presence.firebaseio-demo.com/.info/connected');
connectedRef.on(value,function(isOnline){
if(isOnline.val()){
//如果我们失去了互联网连接,我们希望自己从列表中删除
myUserRef.onDisconnect()。remove();

//设置我们的初始在线状态
setUserStatus(★online);
} else {

//当我们被标记为离线,然后设置正确的状态时,我们需要抓住我们
//可以被标记为离线1)在页面加载或2)当我们输了我们的互联网连接
//暂时。
setUserStatus(currentStatus);
}
});
//}


//辅助函数让我们设置自己的状态。
函数setUserStatus(状态){
//在联机用户列表中设置我们的状态。
currentStatus =状态;
myUserRef.set({name:name,status:status});


//更新我们的GUI以显示某人的在线状态
userListRef.on(child_added,function(snapshot){
var user = snapshot.val();
$(#output)。append($(< div />)。attr(id,snapshot.name()));
$(#+ snapshot.name())。text(user.name +is currently+ user.status);
if(snapshot.name()!= myUserRef.name()){
var $ invite = $('< div id =invite> invite< / div>');
$(#output)。append($ invite);
$($ invite).on('click',function(){
// startGame(user);
console.log('Gegner2:'+ snapshot.name());
console.log('Genger2Name:'+ user.name);
joinGame({id:snapshot.name(),name:user.name,status:user.status});
}) ;
}

});

//更新我们的图形用户界面以删除已经离开的用户的状态
userListRef.on( child_removed,函数(快照){
$(# + snapshot.name())。remove();
});
$ b $ //更新我们的GUI来改变用户的状态
userListRef.on(child_changed,function(snapshot){
var user = snapshot.val() ;
$(#+ snapshot.name())。text(user.name +is currently+ user.status);
});
document.onIdle = function (){
setUserStatus(☆idle);
}
document.onAway = function(){
setUserStatus(☄away);
}
document.onBack =函数(isIdle,isAway){
setUserStatus(★online);
}

setIdleTimeout(5000);
setAwayTimeout 10000);


函数joinGame(opponent){
console.log(opponent);
console.log(opponent.id);
var player2ID = opponent.id;
myUserRef = new Firebase(connectFour.CONFIG.firebaseUrl + opponent.id);
myUserRef.once('value',function(dataSnapshot){
if(dataSnapshot .val()){
beginGame({id:player2ID,name:opponent.name,status:opponent.stat我们});
} else {
alert(game does not exist);
}
});



函数beginGame(player){
console.log(player);
console.log('Id spieler1:'+ gameId);

});

使用此代码,我可以点击邀请,然后我将看到用户的ID 。我也想把这个ID发给beginGame(),但是这并不起作用。
$ b $ p

我的Firebase结构:

游戏

-InmydEpSe5oZcLZUhfU

-InrLM6uxAsoOayOgFce

  -name:Barbara

-status:away


解决方案

为了向其他用户发送消息,您需要该用户监控Firebase中的已知位置。然后,当你想给他们发送消息时,你只需要以某种方式修改那个位置,他们会得到一个回调。这里有一些伪代码:

  var root = new Firebase(...); 
$ b $ //初始化开始侦听消息
root.child(users / inbound-messages)。on(child_added,
function(newMessageSnapshot){
displaySomethingToTheser(newMessageSnapshot.val());
newMessageSnapshot.ref()。remove();
}
);
$ b $ //发送消息给另一个用户
root.child(otherUserId).child(inbound-messages)。push(Hi other user!);


I'm trying to make a "FourConnect"-game with javascript. I want, that there is a list from all online users. This list I've made with the example on the firebase site. Now I want that I can choose one online user and send them a invitation to play with me. So I wrote a function, that all users expect of me have an additional div. When I click on the div this special user should get a confirm box to say okey or cancel. If the user clicks okey the play should begin. I'll save the name and the id from the user. This already works.

My problem is, that I don't know how to send the request to the other user. I tried out many but always the confirm box is on my brwoser not on the browser of the other user.

I looked for solutions on the firebase page and in google but couldn't find anything which solves my problem.

The code I already have:

  var name = prompt("Your name?", "Guest"),
      currentStatus = "★ online";

  // Get a reference to the presence data in Firebase.
  var userListRef = new Firebase(connectFour.CONFIG.firebaseUrl);

  // Generate a reference to a new location for my user with push.
  var myUserRef = userListRef.push();
  var gameId = myUserRef.name();
  document.getElementById('labelGameId').innerHTML = gameId;

  beginGame({id: gameId, name: name, status: currentStatus});
  // Get a reference to my own presence status.
  var connectedRef = new Firebase('http://presence.firebaseio-demo.com/.info/connected');
  connectedRef.on("value", function(isOnline) {
    if (isOnline.val()) {
      // If we lose our internet connection, we want ourselves removed from the list.
      myUserRef.onDisconnect().remove();

      // Set our initial online status.
      setUserStatus("★ online");
    } else {

      // We need to catch anytime we are marked as offline and then set the correct status. We
      // could be marked as offline 1) on page load or 2) when we lose our internet connection
      // temporarily.
      setUserStatus(currentStatus);
    }
  });
//}


  // A helper function to let us set our own state.
  function setUserStatus(status) {
    // Set our status in the list of online users.
    currentStatus = status;
    myUserRef.set({ name: name, status: status });
  }

  // Update our GUI to show someone"s online status.
  userListRef.on("child_added", function(snapshot) {
    var user = snapshot.val();
    $("#output").append($("<div/>").attr("id", snapshot.name()));
    $("#" + snapshot.name()).text(user.name + " is currently " + user.status);
    if(snapshot.name() != myUserRef.name()){
        var $invite = $('<div id="invite">invite</div>');
        $("#output").append($invite);
        $($invite).on('click', function(){
            //startGame(user);
            console.log('Gegner2: '+snapshot.name());
            console.log('Genger2Name: '+user.name);
                joinGame({id: snapshot.name(), name: user.name, status: user.status});
        });
    }

  });

  // Update our GUI to remove the status of a user who has left.
  userListRef.on("child_removed", function(snapshot) {
    $("#" + snapshot.name()).remove();
  });

  // Update our GUI to change a user"s status.
  userListRef.on("child_changed", function(snapshot) {
    var user = snapshot.val();
    $("#" + snapshot.name()).text(user.name + " is currently " + user.status);
  });
  document.onIdle = function () {
    setUserStatus("☆ idle");
  }
  document.onAway = function () {
    setUserStatus("☄ away");
  }
  document.onBack = function (isIdle, isAway) {
    setUserStatus("★ online");
  }

  setIdleTimeout(5000);
  setAwayTimeout(10000);


function joinGame(opponent) {
    console.log(opponent);
    console.log(opponent.id);
    var player2ID = opponent.id; 
    myUserRef = new Firebase(connectFour.CONFIG.firebaseUrl + opponent.id);
    myUserRef.once('value', function(dataSnapshot){
        if(dataSnapshot.val()){
            beginGame({id: player2ID , name: opponent.name, status: opponent.status});
        }else{
            alert("game doesn't exist");
        }
    });

}

function beginGame(player) {
    console.log(player);
    console.log('Id spieler1: '+gameId);

    });

With this code I can click on "invite" and then I will see the ID which the user had. I also wanted to send the ID to beginGame() but this doesn't really works.

My Firebase Structure:

games

-InmydEpSe5oZcLZUhfU

-InrLM6uxAsoOayOgFce

  -name: "Barbara"

  -status: "away"

解决方案

In order to send a message to another user, you need that user to be monitoring a known location in your Firebase. Then when you want to send them a message, you simply modify that location in some way and they'll get a callback. Here's some pseudo code:

var root = new Firebase(...);

//On initialization start listening for messages
root.child("users/inbound-messages").on("child_added", 
  function(newMessageSnapshot) {
    displaySomethingToTheUser(newMessageSnapshot.val());
    newMessageSnapshot.ref().remove();
  }
);

//Send a message to another user
root.child(otherUserId).child("inbound-messages").push("Hi other user!");

这篇关于如何使用Firebase将警报消息发送给特殊的在线用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆