在伺服器端hold住一個連接, 不立即返回, 直到有數據才返回, 這就是長連接技術的原理,本文主要和大家分享php實現長連接方法,希望能幫助到大家。
長連線技術的關鍵在於hold住一個HTTP請求, 直到有新資料時才回應請求, 然後客戶端再次自動發起長連線請求.
那怎麼樣hold住一個請求呢?伺服器端的程式碼可能看起來像這樣的
set_time_limit(0); //这句很重要, 不至于运行超时while (true) 、{ if (hasNewMessage()) { echo json_encode(getNewMessage()); break; } usleep(100000); //避免太过频繁的查询}
沒錯,就是透過循環來實現hold住一個請求, 不至於立即返回. 查詢到有新資料之後才回應請求. 然後客戶端處理資料後,再次發起長連線請求.
客戶端的程式碼是像這樣的
<script type="text/javascript"> (function longPolling() { $.ajax({ 'url': 'server.php', 'data': data, 'dataType': 'json', 'success': function(data) { processData(data); longPolling(); }, 'error': function(data) { longPolling(); } }); })();</script>
##透過長連接, 我們可以開發一個簡易的web聊天室下面, 我們透過redis開發一個簡易的web聊天室
<?php namespace church\LongPolling;use Closure;use church\LongPolling\Queue\RedisQueue;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\JsonResponse;class Server{ public $event = []; public $redisQueue = null; public $request = null; public $response = null; public function __construct() { $this->redisQueue = new RedisQueue(); $this->request = Request::createFromGlobals(); $this->response = new JsonResponse(); } public function on($event, Closure $closure) { if (is_callable($closure)) { $this->event[$event][] = $closure; } } public function fire($event) { if (isset($this->event[$event])) { foreach ($this->event[$event] as $callback) { call_user_func($callback, $this); } } } public function sendMessage($data) { switch ($data['type']) { case 'unicast': //单播 $this->unicast($data['target'], $data['data'], $data['resource']); break; case 'multicast': //组播 foreach ($data['target'] as $target) { $this->unicast($target, $data['data'], $data['resource']); } break; case 'broadcast': //广播 foreach ($this->redisQueue->setQueueName('connections') as $target) { $this->unicast($target, $data['data'], $data['resource']); } break; } $this->fire('message'); } public function unicast($target, $message, $resource = 'system') { $redis_queue = new RedisQueue(); $redis_queue->setQueueName($target)->push($resource . ':' . $message); } public function getMessage($target) { return $this->redisQueue->setQueueName($target)->pop(); } public function hasMessage($target) { return count($this->redisQueue->setQueueName($target)); } public function run() { $data = $this->request->request; while (true) { if ($data->get('action') == 'getMessage') { if ($this->hasMessage($data->get('target'))) { $this->response->setData([ 'state' => 'ok', 'message' => '获取成功', 'data' => $this->getMessage($data->get('target')) ]); $this->response->send(); break; } } elseif ($data->get('action') == 'connect') { $exist = false; foreach ($this->redisQueue->setQueueName('connections') as $connection) { if ($connection == $data->get('data')) { $exist = true; } } if (! $exist) { $this->redisQueue->setQueueName('connections')->push($data->get('data')); } $this->fire('connect'); break; } usleep(100000); } } }
以上是php實作長連接方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!