Wednesday, August 4, 2010

Asynchronous Faye Requests

‹prev | My Chain | next›

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) {
var ret = [];
for (var id in players) {
ret.push(players[id].status);
}
client.publish("/players/all", ret);
});
In the backend, I subscribe to the /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() {
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]);
}
});
};
Last up, I send a request to the /players/query channel so that I will get a reply on the subscribed /players/all:
PlayerList.prototype.initialize_population = function() {
// subscribe to /players/all

this.faye.publish('/players/query', 'all');

setTimeout(function() {subscription.cancel();}, 2000);
};
For good measure, I cancel my subscription to /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