php - Difference between a normal ajax and long polling -
i'm trying understand more long polling "manipulate" website in real time, saw videos , i'm thinking far:
say have old date sql , make echo on it. long polling know if old date not same time time according setinterval function ...?
say want show publication of blog in text in mysql, repende publish new publication, , on page @ time, see publication time (not tell me?), how 1 long polling code know difference between old , new publication? ate not give conflicting or repeating same date engraved on sql.
since initial question difference between 2 techniques is, start this:
ajax polling
using ajax polling update page mean, send request in defined interval server, this:
the client sends request server , server responses immediately.
a simple example (using jquery) this:
setinterval(function(){ $('#mycurrentmoney').load('getcurrentmoney.php'); }, 30000);
the problem is, cause lot of useless requests since there won't new things on every request.
ajax long polling
using ajax long polling mean, client sends request server , server waits new data available before responds. this:
the client sends request , server responds "irregularly". server responds, client send new request server.
the client side this:
refresh = function() { $('#mycurrentmoney').load('getcurrentmoney.php',function(){ refresh(); }); } $(function(){ refresh(); });
what load getcurrentmoney.php
's output current money element , there callback, start new request.
on server side use loop. solve question how server know, new publications: either pass timestamp of newest client available publication server or use time of "long polling start" indiactor:
<? $time = time(); while ($newestpost <= $time) { // note not count execution time on linux , won't run 30 seconds timeout - if wan't save can use loop instead of while sleep(10000); // getlatestposttimestamp() should select in db , timestamp of latest post $newestpost = getlatestposttimestamp(); } // output whatever wan't give client echo "there new posts available";
here won't have "useless" requests.
Comments
Post a Comment