PHP長連接實現(xiàn)與使用方法詳解
本文實例講述了PHP長連接實現(xiàn)與使用方法。分享給大家供大家參考,具體如下:
長連接技術(Long Polling)
在服務器端hold住一個連接, 不立即返回, 直到有數(shù)據(jù)才返回, 這就是長連接技術的原理
長連接技術的關鍵在于hold住一個HTTP請求, 直到有新數(shù)據(jù)時才響應請求, 然后客戶端再次自動發(fā)起長連接請求.
那怎么樣hold住一個請求呢?服務器端的代碼可能看起來像這樣的
set_time_limit(0); //這句很重要, 不至于運行超時 while (true) { if (hasNewMessage()) { echo json_encode(getNewMessage()); break; } usleep(100000); //避免太過頻繁的查詢 }
沒錯,就是通過循環(huán)來實現(xiàn)hold住一個請求, 不至于立即返回. 查詢到有新數(shù)據(jù)之后才響應請求. 然后客戶端處理數(shù)據(jù)后,再次發(fā)起長連接請求.
客戶端的代碼是像這樣的
<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>
一個簡易的聊天室
通過長連接, 我們可以開發(fā)一個簡易的web聊天室
下面, 我們通過redis開發(fā)一個簡易的web聊天室
1. 每一個客戶端發(fā)起長連接時, 在服務器端生成一個消息隊列, 對應該用戶. 然后監(jiān)聽有無新數(shù)據(jù), 有則返回數(shù)據(jù)到客戶端進行處理, 并再起發(fā)起長連接請求.
2. 每一個客戶端發(fā)起消息時, 進行消息隊列的廣播.
下面是代碼片段:
<?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); } } }
長連接避免了過于頻繁的輪詢. 但服務器維持一個長連接也有額外的資源消耗. 大并發(fā)時性能不理想. 在小型應用里面可以考慮使用
更建議客戶端使用html5的websocket協(xié)議, 服務器端使用swoole.
有關swoole, 你可以查看官網(wǎng):https://www.swoole.com/
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php socket用法總結》、《php字符串(string)用法總結》、《PHP數(shù)學運算技巧總結》、《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP數(shù)據(jù)結構與算法教程》、《php程序設計算法總結》及《PHP網(wǎng)絡編程技巧總結》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
PHP使用mongoclient簡單操作mongodb數(shù)據(jù)庫示例
這篇文章主要介紹了PHP使用mongoclient簡單操作mongodb數(shù)據(jù)庫,結合實例形式分析了php使用mongoclient針對MongoDB數(shù)據(jù)庫的連接、增刪改查及相關函數(shù)使用技巧,需要的朋友可以參考下2019-02-02php數(shù)組實現(xiàn)根據(jù)某個鍵值將相同鍵值合并生成新二維數(shù)組的方法
這篇文章主要介紹了php數(shù)組實現(xiàn)根據(jù)某個鍵值將相同鍵值合并生成新二維數(shù)組的方法,涉及php數(shù)組的遍歷、賦值相關運算技巧,需要的朋友可以參考下2017-04-04