Tp3.2 Workerman使用
阿新 • • 發佈:2021-07-17
workerman使用
檢測是否支援
% curl -Ss http://www.workerman.net/check.php | php
PHP Version >= 5.3.3 [OK]
Extension pcntl check [OK]
Extension posix check [OK]
composer 安裝
% composer require workerman/workerman Using version ^4.0 for workerman/workerman ./composer.json has been updated Running composer update workerman/workerman Loading composer repositories with package information Updating dependencies Lock file operations: 1 install, 0 updates, 0 removals - Locking workerman/workerman (v4.0.19) Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Downloading workerman/workerman (v4.0.19) - Installing workerman/workerman (v4.0.19): Extracting archive 1 package suggestions were added by new dependencies, use `composer suggest` to see details. Generating autoload files 9 packages you are using are looking for funding. Use the `composer fund` command to find out more!
核心程式碼
<?php /** * workerman */ namespace Index\Action; use Common\Util\JsonUtil; use Workerman\Worker; class WsAction extends CommonAction { public function start() { global $worker; $worker = new Worker('websocket://0.0.0.0:'.C('WS_PORT')); // 8000 // 這裡程序數必須設定為1 $worker->count = 1; // worker程序啟動後建立一個內部通訊埠 $worker->onWorkerStart = function ($worker) { // 開啟一個內部埠,方便內部系統推送資料,Text協議格式 文字+換行符 $inner_text_worker = new Worker('Text://0.0.0.0:'.C('WS_INNER_PORT')); // 8001 $inner_text_worker->onMessage = function ($connection, $buffer) { global $worker; // $data陣列格式,裡面有uid,表示向那個uid的頁面推送資料 $data = JsonUtil::jsonDecode($buffer); $uid = $data['uid']; // 傳送資料 if ($uid) { $res = $this->sendMessageByUid($uid, $data['data']); } else { $res = $this->broadcast($data['data']); } // 返回推送結果 $connection->send($res ? 'ok' : 'fail'); echo "inner text Msg $uid \n"; }; $inner_text_worker->listen(); echo "Start \n"; }; // 新增加一個屬性,用來儲存uid到connection的對映 $worker->uidConnections = array(); // 當有客戶端發來訊息時執行的回撥函式 $worker->onMessage = function ($connection, $data) use ($worker) { // 判斷當前客戶端是否已經驗證,既是否設定了uid if (!isset($connection->uid)) { // 沒驗證的話把第一個包當做uid(這裡為了方便演示,沒做真正的驗證) $connection->uid = $data; /* 儲存uid到connection的對映,這樣可以方便的通過uid查詢connection, * 實現針對特定uid推送資料 */ $worker->uidConnections[$connection->uid] = $connection; } echo $connection->uid."msg \n"; }; //當客戶端連線時 $worker->onConnect = function ($connection){ echo $connection->id."connect \n"; }; // 當有客戶端連線斷開時 $worker->onClose = function ($connection) use ($worker) { global $worker; if (isset($connection->uid)) { // 連線斷開時刪除對映 unset($worker->uidConnections[$connection->uid]); } echo $connection->uid."close \n"; }; // 執行所有的worker(其實當前只定義了一個) Worker::runAll(); } // 向所有驗證的使用者推送資料 public function broadcast($message) { global $worker; foreach ($worker->uidConnections as $connection) { $connection->send($message); } return true; } // 針對uid推送資料 public function sendMessageByUid($uid, $message) { global $worker; if (isset($worker->uidConnections[$uid])) { $connection = $worker->uidConnections[$uid]; $connection->send($message); return true; } return false; } }
啟動服務,必須通過php指令啟動
% php -f index.php Ws/start start Workerman[index.php] start in DEBUG mode ------------------------------------------- WORKERMAN -------------------------------------------- Workerman version:4.0.19 PHP version:5.6.40 -------------------------------------------- WORKERS --------------------------------------------- proto user worker listen processes status tcp jiqing none websocket://0.0.0.0:8000 1 [OK] -------------------------------------------------------------------------------------------------- Press Ctrl+C to stop. Start success. Start
% php -f index.php Ws/start start -d
Workerman[index.php] start in DAEMON mode
------------------------------------------- WORKERMAN --------------------------------------------
Workerman version:4.0.19 PHP version:5.6.40
-------------------------------------------- WORKERS ---------------------------------------------
proto user worker listen processes status
tcp jiqing none websocket://0.0.0.0:8000 1 [OK]
--------------------------------------------------------------------------------------------------
Input "php index.php Ws/start stop" to stop. Start success.
% php -f index.php Ws/start stop
Workerman[index.php] stop
Workerman[index.php] is stopping ...
Workerman[index.php] stop success
客戶端連線
ws = new WebSocket("ws://127.0.0.1:8000");
ws.onopen = function() {
alert("連線成功");
ws.send('uid1');
};
ws.onmessage = function(e) {
alert(e.data);
};
服務端主動傳送訊息
public function send()
{
// 建立socket連線到內部推送埠
$client = stream_socket_client('tcp://127.0.0.1:'.C('WS_INNER_PORT'), $errno, $errmsg, 1);
// 推送的資料,包含uid欄位,表示是給這個uid推送
$data = array('uid' => '', 'data' => JsonUtil::jsonEncode(['name'=>'張三','age'=>15]));
// 傳送資料,注意8001埠是Text協議的埠,Text協議需要在資料末尾加上換行符
fwrite($client, json_encode($data) . "\n");
// 讀取推送結果
$res = trim(fread($client, 8192),"\n");
$this->json->ok($res);
}