There are two ways in which PHP implements real-time communication.

Source: Internet
Author: User

There are generally two ways to achieve real-time communication:
Socket or comet. Socket is a good solution, the problem is not all browsers are compatible, server-side implementation is a little bit cumbersome. By contrast, comet ("Server Push" based on HTTP long connections) is easier to implement and compatible with all browsers. So this time it's about Comet's PHP implementation.

Comet also has several implementations, such as IFRAME, HTTP long request, this article mainly discusses the HTTP long request for real-time communication.

First talk about the HTTP long link is how, the popular point is that the server is not a request to directly spit data, but in that suppress AH suppress, has been suppressed to suppress, only to tell you the results of implementation.

As for how long to suppress, look at the specific application, if suppressed too long, the server resource occupancy will also be a problem.

Now we are going to implement real-time communication by this method (in fact, quasi-real-time), first of all, to say the principle:

1. The client initiates an AJAX long link query, and then the server starts executing code, mainly to check if a file has been updated, if not, sleep for a while, wake up and check
2. If the client also initiates a query link (normal request), after the server receives the request, processing it, and then updating the modify time of a particular file.
3. The background code of the first AJAX query is still executing, and a file is updated, indicating that a new request has been made and the corresponding result is output.
4. The callback of the first AJAX query is triggered, the page is updated, and then a new Ajax long link is launched

<?php//novcomet.php class Novcomet {const COMET_OK = 0; Const comet_changed = 1; private $_tries; private $_var; Private $_ Sleep Private $_ids = Array (); Private $_callback = null; Public function __construct ($tries = $, $sleep = 2){$this->_tries =$tries;$this->_sleep =$sleep; }  Public functionSetVar ($key,$value)    { $this->_vars[$key] =$value; }  Public functionSettries ($tries)    { $this->_tries =$tries; }  Public functionSetsleeptime ($sleep)    { $this->_sleep =$sleep; }  Public functionSetcallbackcheck ($callback)    { $this->_callback =$callback; } ConstDefault_comet_path = "/dev/shm/%s.comet"; Public functionRun () {if(Is_null($this->_callback)) {$defaultCometPAth= self::D efault_comet_path;$callback=function($id) Use($defaultCometPAth) {$cometFile=sprintf($defaultCometPAth,$id);return(Is_file($cometFile)) ?Filemtime($cometFile): 0;        }; } Else{$callback=$this-_callback; }  for($i= 0;$i<$this->_tries;$i++) {foreach($this->_vars as $id=$timestamp) {if((integer)$timestamp= = 0) {$timestamp= Time(); } $fileTimestamp=$callback($id);if($fileTimestamp>$timestamp) {$out[$id] =$fileTimestamp; } Clearstatcache(); } if(Count($out) > 0) {returnJson_encode (Array(' s ' = = self::comet_changed, ' k ' = =$out)); } Sleep($this-_sleep); } returnJson_encode (Array(' s ' = + Self::COMET_OK)); }  Public functionPublish$id)    { returnJson_encode (Touch(sprintf(Self::D efault_comet_path,$id))); }} <?php//comet.php include (' novcomet.php '); $comet = new Novcomet (); $publish = Filter_input (input_get, ' Publish ', Filter_san itize_string); if ($publish! = ") {echo $comet->publish ($publish);} else {foreach (Filter_var_array ($_get[' subscribed '), Filter_sa Nitize_number_int) as $key = $value) {$comet->setvar ($key, $value);} echo $comet->run (); }    functionSend (msg) {$.Ajax ({data: {' msg ': Msg}, type: ' Post ', url: ' {: U (' live/sendmsg ')} ', Success:function(response) {//alert (response);; }})} $ (document). Ready (function() {connect (); $("#btn"). Click (function(){varmsg = $ (' #msg ').Val ();            Send (msg); Msg. HTML (');    }); })       Public functionSendmsg () {$filename= './uploads/live/'. ' Data.json ';if($_post[' msg ']!= ') {file_put_contents($filename,$_post[' msg ']);$this->ajaxreturn ($_post, ' OK ', 100); die(); }Else{$this->ajaxreturn ($_post, ' on ', 0); die(); }            }<! DOCTYPE html Public"-//w3c//dtd XHTML 1.1//en" "Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" > vartimestamp = 0;varurl = ' backend.php ';varError =false;//using AJAX to establish a connection to a PHP-side handler (a long-time connection via a recursive call) function connect () {$.Ajax ({data: {' timestamp ': timestamp},URL: URL,type: ' Get ',Timeout: 0,Success:function(response) {vardata = JSON.Parse (response); Error=false; Timestamp= Data.timestamp;if(data.msg! = undefined && data.msg! = "")                {                    $("#content"). Append ("<div>" + data.msg + "</div>"); }            },Error:function() {Error=true; SetTimeout (function() {connect ();}, 5000); }, Complete:function(){if(Error)//Delay 5s Reconnect SetTimeout (function () {connect ();}, () (), if request has an error, else connect ();            }        })    } //Send Message function Send (msg) {$.Ajax ({data: {' msg ': Msg},type: ' Get ',URL:URL}) } //Create a long-time connection $ (document). Ready (function () {Connect (); }) </script> //The set request run time is not limited, resolving the request Ini_set ("Max_execution_time", "0") for the end of the server run time, $filename = DirName (__file__). /data.txt '; $msg = isset ($_get[' msg ")? $_get[' msg ']: '; Determines whether the modified content submitted by the page is empty, writes the content to the file, and interrupts the process if ($msg! = "){file_put_contents($filename,$msg);Exit;} /*gets the file last modified timestamp and the most recent file modification timestamp * File Last modified timestamp initial default value is 0 * Last file modification timestamp obtained by Function filemtime ()*/ $lastmodif=isset($_get[' timestamp ']) ?$_get[' timestamp ']: 0;Clearstatcache();//clears the file state cache $currentmodif = Filemtime ($filename);/* If the currently returned file modifies the Unix timestamp less than or equal to the last modified time,*indicates that the file does not have an update and does not require push messages*if the currently returned file modifies the Unix timestamp greater than the last modified time* Indicates that the file has been updated to output the modified content as a push message */ while($currentmodif<=$lastmodif){ Usleep(10000);//hibernate 10ms frees CPU occupied Clearstatcache ();//Clears file status cache $currentmodif = Filemtime ($filename);}//Push information processing (need to push the description file has changed, the push message contains the modification time, content) $response = Array (); $response [' msg '] = file_get_contents ($filename); $ response[' timestamp '] = $currentmodif; echo Json_encode ($response); Flush ();?>

There are two ways in which PHP implements real-time communication.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.