Sunday, May 2, 2010

Comet (sort of) and Fab.js

‹prev | My Chain | next›

Tonight, I explore comet with fab.js. I have my little <canvas> room sending coordinate events to fab.js. Now I'd like to push them to listening clients.

First up, I give a place for a client to access a view-only look at the room:
  ( /view/ )
( function(){
listeners.push( this );
} )
Very straight forward: the requesting client is stored in an array of listeners to be called later. That later time happens when I move my character around in the <canvas> room:
  ( /move/ )

(
function () {
var out = this;
return function listener( obj ) {
if ( !obj ) out();
else if ( obj.body ) {
broadcast(obj);
}
return listener;
};
}
)
The broadcast function should iterate over each listener and send the coordinates:
function broadcast(obj) {
listeners.forEach(
function(listener) {
listener(obj);
}
);
}
To test this out, I drop down to an unbuffered curl session:
strom@whitefall:~/repos/fab$ curl http://localhost:4011/view -Ni
HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked

{"id":"me","x":192,"y":360}{"id":"me","x":135,"y":226}{"id":"me","x":381,"y":317}
Cool! That seems to have done the trick. I am indeed broadcasting.

I run into a problem that I am unable to solve, however. I cannot use that information to have an effect in the browser. I change the broadcast function to debug the JSON in the browser's console:
function broadcast(obj) {
listeners.forEach(
function(listener) {
//listener(obj);
// puts("sending: " + obj.body);
listener({body:'<script type="text/javascript">console.debug(\'' + obj.body + '\')</script>'+"\n\n"});
}
);
}
My curl client sees this change:
cstrom@whitefall:~/repos/fab$ curl http://localhost:4011/view -Ni
HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked

<script type="text/javascript">console.debug('{"id":"me","x":276,"y":123}')</script>

<script type="text/javascript">console.debug('{"id":"me","x":365,"y":208}')</script>
But nothing happens in my browser's console. Ultimately, I will probably look into web sockets to accomplish this, but I would at least like to understand comet well enough to do something like this, so...

I will pick back up with this tomorrow.

Day #91

No comments:

Post a Comment