ThinkPHP部署Workerman的成功使用示例
本文介紹thinkphp中關(guān)于composer集成workerman的方法,并解決了安裝過(guò)程 中遇到的錯(cuò)誤,實(shí)現(xiàn)了和woerkman進(jìn)行握手和通信的demo。用戶可以在此基礎(chǔ)上按自己的邏輯實(shí)現(xiàn)一個(gè)聊天系統(tǒng)或者客服系統(tǒng)。
一、安裝擴(kuò)展包 composer require topthink/think-worker直接執(zhí)行:composer require topthink/think-worker=1.0.* 即可成功
二、新建 server.php#!/usr/bin/env php<?phpdefine('APP_PATH', __DIR__ . '/application/');define('BIND_MODULE','push/Worker');// 加載框架引導(dǎo)文件require __DIR__ . '/thinkphp/start.php';三、新建Worker.phpphp think make:controller push/Worker
即可,將里面的內(nèi)容替換如下所示:
<?phpnamespace app\push\controller;use think\Controller;use think\Request;use think\worker\Server;use think\Cache;class Worker extends Server{ protected $socket = 'websocket://0.0.0.0:2346'; protected $processes = 1; protected $uidConnections = array(); static $count = 0; /** * 收到信息 * @param $connection * @param $data */ public function onMessage($connection, $data) {$retdata=json_decode($data,true);$uid=$retdata['id'];$message=$retdata['msg'];if(isset($this->uidConnections[$uid])){ $connection = $this->uidConnections[$uid]; $connection->send($message); // return true;}$connection->send('我收到你的信息了333='.$retdata['msg']); } /** * 當(dāng)連接建立時(shí)觸發(fā)的回調(diào)函數(shù) * @param $connection */ public function onConnect($connection) {$this->uidConnections[$connection->id] = $connection;$connection->send('你連接了我='.$connection->id); } // 針對(duì)uid推送數(shù)據(jù) public function sendMessageByUid($uid, $message) {if(isset($this->uidConnections[$uid])){ $connection = $this->uidConnections[$uid]; $connection->send($message); return true;}return false; } /** * 當(dāng)連接斷開(kāi)時(shí)觸發(fā)的回調(diào)函數(shù) * @param $connection */ public function onClose($connection) { } /** * 當(dāng)客戶端的連接上發(fā)生錯(cuò)誤時(shí)觸發(fā) * @param $connection * @param $code * @param $msg */ public function onError($connection, $code, $msg) {echo 'error $code $msg\n'; } /** * 每個(gè)進(jìn)程啟動(dòng) * @param $worker */ public function onWorkerStart($worker) { }}四、執(zhí)行 php server.php start遇到禁用函數(shù)就去對(duì)應(yīng)的PHP里面把禁用函數(shù)刪除 (此命令可以放到Supervisor的守護(hù)進(jìn)程里面去),并且查看端口是否運(yùn)行,寶塔里面也要放行對(duì)應(yīng)的端口 2346
測(cè)試遠(yuǎn)程連接: telnet localhost 2346 localhost改成外網(wǎng)ip即可,這個(gè)走通了,前端就能直接連接了
linux 退出Telnet命令 先輸入命令:CTRL+]然后再輸入命令:quit
五、前端代碼<!DOCTYPE html><html lang='en'><head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <title>Title</title></head><body><script> ws = new WebSocket('ws://118.**.***.207:2346'); ws.onopen = function() {console.log('連接成功');ws.send('tom');console.log('給服務(wù)端發(fā)送一個(gè)字符串:tom'); }; ws.onmessage = function(e) {console.log('收到服務(wù)端的消息:' + e.data); };</script></body></html>六、前端開(kāi)兩個(gè)端口即可進(jìn)行相互通訊:ws.send('{'id':'2','msg':'21111111111110'}');重點(diǎn)在這:因?yàn)樵谶@里需要用到服務(wù)端給客戶端推送,用到了text服務(wù)
WorkerMan中php后端及時(shí)推送消息給客戶端原理:1、建立一個(gè)websocket Worker,用來(lái)維持客戶端長(zhǎng)連接
2、websocket Worker內(nèi)部建立一個(gè)text Worker
3、websocket Worker 與 text Worker是同一個(gè)進(jìn)程,可以方便的共享客戶端連接
4、某個(gè)獨(dú)立的php后臺(tái)系統(tǒng)通過(guò)text協(xié)議與text Worker通訊
5、text Worker操作websocket連接完成數(shù)據(jù)推送
代碼及步驟//push.php<?phpuse Workerman\Worker;require_once './vendor/workerman/workerman/Autoloader.php';// 初始化一個(gè)worker容器,監(jiān)聽(tīng)1234端口$worker = new Worker('websocket://0.0.0.0:1234');///* * 注意這里進(jìn)程數(shù)必須設(shè)置為1,否則會(huì)報(bào)端口占用錯(cuò)誤 * (php 7可以設(shè)置進(jìn)程數(shù)大于1,前提是$inner_text_worker->reusePort=true) */$worker->count = 1;// worker進(jìn)程啟動(dòng)后創(chuàng)建一個(gè)text Worker以便打開(kāi)一個(gè)內(nèi)部通訊端口$worker->onWorkerStart = function($worker){ // 開(kāi)啟一個(gè)內(nèi)部端口,方便內(nèi)部系統(tǒng)推送數(shù)據(jù),Text協(xié)議格式 文本+換行符 $inner_text_worker = new Worker('text://0.0.0.0:5678'); $inner_text_worker->onMessage = function($connection, $buffer) {// $data數(shù)組格式,里面有uid,表示向那個(gè)uid的頁(yè)面推送數(shù)據(jù)$data = json_decode($buffer, true);$uid = $data['uid'];// 通過(guò)workerman,向uid的頁(yè)面推送數(shù)據(jù)$ret = sendMessageByUid($uid, $buffer);// 返回推送結(jié)果$connection->send($ret ? 'ok' : 'fail'); }; // $connection->send('你好,你連接我了'); // ## 執(zhí)行監(jiān)聽(tīng) ## $inner_text_worker->listen();};// 新增加一個(gè)屬性,用來(lái)保存uid到connection的映射$worker->uidConnections = array();// 當(dāng)有客戶端發(fā)來(lái)消息時(shí)執(zhí)行的回調(diào)函數(shù)$worker->onMessage = function($connection, $data){ $data=json_decode($data,true); $connection->send('99897'); global $worker; // 判斷當(dāng)前客戶端是否已經(jīng)驗(yàn)證,既是否設(shè)置了uid if(!isset($connection->uid)) {// 沒(méi)驗(yàn)證的話把第一個(gè)包當(dāng)做uid(這里為了方便演示,沒(méi)做真正的驗(yàn)證)$connection->uid = $data['id'];/* 保存uid到connection的映射,這樣可以方便的通過(guò)uid查找connection, * 實(shí)現(xiàn)針對(duì)特定uid推送數(shù)據(jù) */$worker->uidConnections[$connection->uid] = $connection;$connection->send('9980'.$data['msg']);return; }else{ $connection->send('998123'); }};// 當(dāng)有客戶端連接斷開(kāi)時(shí)$worker->onClose = function($connection){ global $worker; if(isset($connection->uid)) {// 連接斷開(kāi)時(shí)刪除映射unset($worker->uidConnections[$connection->uid]); }};// 向所有驗(yàn)證的用戶推送數(shù)據(jù)function broadcast($message){ global $worker; foreach($worker->uidConnections as $connection) {$connection->send($message); }}// 針對(duì)uid推送數(shù)據(jù)function sendMessageByUid($uid, $message){ global $worker; if(isset($worker->uidConnections[$uid])) {$connection = $worker->uidConnections[$uid];$connection->send($message);return true; } return false;}運(yùn)行所有的workerWorker::runAll();啟動(dòng)后端服務(wù) php push.php start -d
前端接收推送的js代碼<!DOCTYPE html><html lang='en'><head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <title>Title</title></head><body><script> var ws = new WebSocket('ws://118.**.**.207:1234'); ws.onopen = function(){var uid = 'uid1';ws.send(uid);console.log('給服務(wù)端發(fā)送一個(gè)字符串:'+uid); }; ws.onmessage = function(e){// alert(e.data);console.log('收到服務(wù)端的消息:' + e.data); };</script></body></html>后端推送消息的代碼// 建立socket連接到內(nèi)部推送端口$client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);// 推送的數(shù)據(jù),包含uid字段,表示是給這個(gè)uid推送$data = array('uid'=>'uid1', 'percent'=>'88%');// 發(fā)送數(shù)據(jù),注意5678端口是Text協(xié)議的端口,Text協(xié)議需要在數(shù)據(jù)末尾加上換行符fwrite($client, json_encode($data).'\n');// 讀取推送結(jié)果echo fread($client, 8192);后端推送消息的代碼和push.php監(jiān)聽(tīng)同一個(gè)端口
push.php和前端監(jiān)聽(tīng)同一個(gè)websocket端口
通過(guò)后端推送消息的代碼向push.php推送數(shù)據(jù),
push.php接受到數(shù)據(jù)后通過(guò)處理 利用websocket往前端推送數(shù)據(jù)
到此這篇關(guān)于ThinkPHP部署Workerman的成功使用示例的文章就介紹到這了,更多相關(guān)ThinkPHP部署Workerman內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ThinkPHP5 框架引入 Go AOP,PHP AOP編程項(xiàng)目詳解2. ThinkPHP5 通過(guò)ajax插入圖片并實(shí)時(shí)顯示(完整代碼)3. Thinkphp5分頁(yè)后攜帶參數(shù)跳轉(zhuǎn)傳遞功能實(shí)現(xiàn)4. thinkphp6中Redis 的基本使用方法詳解5. php使用goto實(shí)現(xiàn)自動(dòng)重啟swoole、reactphp、workerman服務(wù)的代碼6. Thinkphp6 配置并使用redis圖文詳解7. Thinkphp3.2.3反序列化漏洞實(shí)例分析8. IOS蘋果AppStore內(nèi)購(gòu)付款的服務(wù)器端php驗(yàn)證方法(使用thinkphp)9. ThinkPHP基于think-queue的隊(duì)列插件實(shí)現(xiàn)消息推送10. Vue+thinkphp5.1+axios實(shí)現(xiàn)文件上傳
