Up today, I am going to attempt to asynchronously query a faye channel. When a player first enter a room in my (fab) game, the client-side room needs to be able to draw all of the players already in the room. I had been doing that query via comet, but, now that my comet interface is gone, I need to accomplish the same thing in faye.
First up, I add a faye subscription in the fab.js backend. This subscription will listen for requests for a list of all players in the room. When it sees such a request, it will need to publish that list on another faye channel:
client.subscribe("/players/query", function(q) {In the backend, I subscribe to the
var ret = [];
for (var id in players) {
ret.push(players[id].status);
}
client.publish("/players/all", ret);
});
/players/query
. I am not sure if that channel name will stick, but it gives me a nice way to segment off the query message from broadcast responses. Speaking off broadcasting, I respond to player queries on the /players/all
channel. That gets done right inside the callback to /players/query
—in response to a /players/query
, I reply immediately on the /players/all
channel.With the backend set, I need to setup the frontend. First, I subscribe to the
/players/all
channel. When messages are sent to that channel, I assume that they will be a list of players in the room. I iterate over each player, adding it to the client-side representation of the room:PlayerList.prototype.initialize_population = function() {Last up, I send a request to the
var self = this;
var subscription = this.faye.subscribe('/players/all', function(players) {
for (var i=0; i<players.length; i++) {
self.add_player(players[i]);
}
});
};
/players/query
channel so that I will get a reply on the subscribed /players/all
:PlayerList.prototype.initialize_population = function() {For good measure, I cancel my subscription to
// subscribe to /players/all
this.faye.publish('/players/query', 'all');
setTimeout(function() {subscription.cancel();}, 2000);
};
/players/all
after 2 seconds. The add_player
method is setup such that calling it several time would do no harm, but why keep the subscription in place if it is not needed?That is a good stopping point for the night. Up tomorrow, I hope to remove the rest of my old comet code in favor of faye pub-sub messaging goodness.
Day #185
No comments:
Post a Comment