|
|
General Usage
var listen = new pi.comet;
listen.environment.setUrl("push.php");
listen.event.push = function(RESPONSE){
alert(RESPONSE); // server sends data to this function
}
listen.send();How it works?
Pi Comet provides that serverside programs can access javascript functions and transfer data. The transfer path for this process is created by browser with 'pi.comet' object.
So, first you have to create a new pi.comet object:
var listen = new pi.comet;
Then, you have to show the object, the file to transfer with.
var listen = new pi.comet;
listen.environment.setUrl("push.php");In that example, we've defined a new transfer path with 'push.php'. 'push.php' sends new data to pi.comet.event object's push method. We have to define this method to get data.
var listen = new pi.comet;
listen.environment.setUrl("push.php");
listen.event.push = function(RESPONSE){
alert(RESPONSE);
}Last we have to run the 'send' function to transfer.
var listen = new pi.comet;
listen.environment.setUrl("push.php");
listen.event.push = function(RESPONSE){
alert(RESPONSE);
}
listen.send();Serverside Pushing
You have to create an infinite loop, and print the data which will be updated each time.
loop {
print "";
flush;
sleep(10)
}The print process must be in 4 different ways because of the browsers' behavior to comet. If you use PHP, you can use my 'pushData' function to print data easily: (Note: pi.py module is available for python users now)
function pushData($data,$type,$name){
switch($type){
case 1:
echo "<end />".$data;
echo str_pad('',4096)."\n";
break;
case 2:
header("Content-type: application/x-dom-event-stream");
print "Event: $name\n";
print "data: $data\n\n";
break;
case 3:
print "<script>parent._cometObject.event.push(\"".$data."\")</script>";
break;
}
}Comet request always sends extra 2 arguments. One of these is 'cometType', and the other is 'cometName'. First send data (which you will print) then these two arguments to 'pushData' function.You can find this function at downloads page.
If you want to adapt this function to another language, be aware of these:
- If 'cometType' value is "1", you have to put "<end />" to top of every loops to split data. Webkit needs some different methods for flush process, you can get more information from http://en.wikipedia.org/wiki/Comet_(programming)
- If 'cometType' value is "2", your program have to print special code for Opera. For more information: http://labs.opera.com/news/2006/09/01/
- Third one is for Internet Explorer You must send data to "parent.cometObject.event.push" function in every 'print' step with a new script block.
Sign in to add a comment
