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