If the English language is OK, you can directly read this article
There are two methods to implement real-time communication:
Socket or comet. Socket is a better solution. The problem is that not all browsers are compatible, and server implementation is a little troublesome. In contrast, comet (based on HTTP persistent connection "server push") is more convenient and compatible with all browsers. So this time we will talk about the PHP implementation of comet.
Comet also has several implementation methods, such as IFRAME and HTTP long request. For the differences between the two, refer to this article. This article mainly discusses how to implement real-time communication through HTTP long request.
Let's talk about how HTTP persistent links are going. In other words, the server doesn't spit data directly when it receives a request, but it's stuck there, and it's stuck, to tell you the execution result.
<? PHP $ COUNT = 10; for ($ I = 0; $ I <$ count; $ I ++) {// do something... sleep (2);} echo 'throttling me ';
As for how long it takes, it depends on the specific application. If it takes too long, the occupation of server resources will also be a problem.
Now we need to use this method to implement real-time communication (in fact, quasi-Real-Time). let's first talk about the principle:
1. The client initiates an Ajax persistent link query, and then the server starts to execute code, mainly to check whether a file is updated. If not, wait for a while (sleep) and then wake up and check
2. If the client initiates another query Link (normal request), the server will process the request after receiving it, and update the modify time of a specific file after processing.
3. The background code for the first Ajax query is still being executed. If a file is updated, a new request is sent and the corresponding result is output.
4. The callback of the first Ajax query is triggered, the page is updated, and a new long Ajax link is initiated.
Actual client
This Code indicates that there is a novcomet object that registers the customalert and customalert2 events. When the page is loaded, the listening events are added to the two buttons, when you click "novcomet", the customalert or customalert2 event is published, and novcomet executes the run method.
Novcomet
//NovComet.jsNovComet = { sleepTime: 1000, _subscribed: {}, _timeout: undefined, _baseurl: "comet.php", _args: '', _urlParam: 'subscribed', subscribe: function(id, callback) { NovComet._subscribed[id] = { cbk: callback, timestamp: NovComet._getCurrentTimestamp() }; return NovComet; }, _refresh: function() { NovComet._timeout = setTimeout(function() { NovComet.run() }, NovComet.sleepTime); }, init: function(baseurl) { if (baseurl!=undefined) { NovComet._baseurl = baseurl; } }, _getCurrentTimestamp: function() { return Math.round(new Date().getTime() / 1000); }, run: function() { var cometCheckUrl = NovComet._baseurl + '?' + NovComet._args; for (var id in NovComet._subscribed) { var currentTimestamp = NovComet._subscribed[id]['timestamp']; cometCheckUrl += '&' + NovComet._urlParam+ '[' + id + ']=' + currentTimestamp; } cometCheckUrl += '&' + NovComet._getCurrentTimestamp(); $.getJSON(cometCheckUrl, function(data){ switch(data.s) { case 0: // sin cambios NovComet._refresh(); break; case 1: // trigger for (var id in data['k']) { NovComet._subscribed[id]['timestamp'] = data['k'][id]; NovComet._subscribed[id].cbk(data.k); } NovComet._refresh(); break; } }); }, publish: function(id) { var cometPublishUrl = NovComet._baseurl + '?' + NovComet._args; cometPublishUrl += '&publish=' + id; $.getJSON(cometPublishUrl); }};
The run method of novcomet first concatenates several previously registered events into a URL, and uses "[]", which is similar :? Subscribed [customalert] = 1300016814 & subscribed [customalert2] = 1300016814 & 1300016825. After receiving this message, PHP will get the $ _ Get [subscribed] array, the last timestamp is used to prevent the request from being cached. If the s value of the data transmitted from the background is 0, nothing happens. The execution will continue after 1 second. the value of S is 1, indicating that the publish event of novcomet is triggered, and the corresponding callback is called. After the publish method is executed, a structure similar:
? Publish = a URL like customalert is sent to the background. If the pubish parameter is detected in the background, obtain the value of the parameter and update the mtime of the corresponding file.
Server
<?php// comet.phpinclude('NovComet.php');$comet = new NovComet();$publish = filter_input(INPUT_GET, 'publish', FILTER_SANITIZE_STRING);if ($publish != '') { echo $comet->publish($publish);} else { foreach (filter_var_array($_GET['subscribed'], FILTER_SANITIZE_NUMBER_INT) as $key => $value) { $comet->setVar($key, $value); } echo $comet->run();}
If you receive the publish parameter, output it directly. Otherwise, run the run method. Check the code for the run method.
<?php// NovComet.phpclass 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 = 20, $sleep = 2) { $this->_tries = $tries; $this->_sleep = $sleep; } public function setVar($key, $value) { $this->_vars[$key] = $value; } public function setTries($tries) { $this->_tries = $tries; } public function setSleepTime($sleep) { $this->_sleep = $sleep; } public function setCallbackCheck($callback) { $this->_callback = $callback; } const DEFAULT_COMET_PATH = "/dev/shm/%s.comet"; public function run() { if (is_null($this->_callback)) { $defaultCometPAth = self::DEFAULT_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) { return json_encode(array('s' => self::COMET_CHANGED, 'k' => $out)); } sleep($this->_sleep); } return json_encode(array('s' => self::COMET_OK)); } public function publish($id) { return json_encode(touch(sprintf(self::DEFAULT_COMET_PATH, $id))); }}
You can see that when publish is created, a file named after $ ID is created. During Run, if the $ ID file exists and the timestamp is greater than the timestamp corresponding to the saved $ ID (set by setvar), the $ id event is triggered, put the $ ID in the $ out array after processing, and then judge whether the $ out array is empty. If not, a piece of JSON is output.
If no event is triggered within a period of time (the for loop execution is complete), a piece of JSON is output, indicating that the frontend execution is complete, but there is no new situation.
Description
- Multiple events can be monitored/published on the client.
- When listening for an event, you can send a callback, so that when receiving the data, the callback
- When listening for an event, a timestamp is sent.
- When the event is publish, a request is sent to the backend and a new timestamp is passed.
- The server does not execute all the time. If no request is triggered within the specified time, the operation ends.
- The client repeats the preceding process (setTimeout & novcomet. Run ())
The last illustration is as follows:
1. After running for a period of time, the server stops executing the publish event.
2. The server returns a piece of JSON
3. When the client triggers an event, the server receives the event and returns a new JSON
4. Callback triggered
5. The client enters the next Ajax persistent link query
From: http://blog.leezhong.com/tech/2011/03/21/php-comet.html