前言
本文主要給大家介紹了關(guān)于Yii2結(jié)合Workerman的websocket的相關(guān)內(nèi)容,兩者都是好東西,我就想著能不能結(jié)合起來(lái),這樣Yii2出現(xiàn)瓶頸的時(shí)候有些業(yè)務(wù)就可以平滑地遷移到Workerman中。下面話不多說(shuō)了,來(lái)隨著小編來(lái)一起看看詳細(xì)的介紹吧
步驟如下
1、安裝workerman
composer require workerman/workerman
2、啟動(dòng)workerman
創(chuàng)建commands/WorkermanWebSocketController.php文件
創(chuàng)建actionIndex()函數(shù),用來(lái)啟動(dòng),代碼如下
public function actionIndex(){ if ('start' == $this->send) { try { $this->start($this->daemon); } catch (/Exception $e) { $this->stderr($e->getMessage() . "/n", Console::FG_RED); } } else if ('stop' == $this->send) { $this->stop(); } else if ('restart' == $this->send) { $this->restart(); } else if ('reload' == $this->send) { $this->reload(); } else if ('status' == $this->send) { $this->status(); } else if ('connections' == $this->send) { $this->connections(); }}
添加初始化模塊
public function initWorker(){ $ip = isset($this->config['ip']) ? $this->config['ip'] : $this->ip; $port = isset($this->config['port']) ? $this->config['port'] : $this->port; $wsWorker = new Worker("websocket://{$ip}:{$port}"); // 4 processes $wsWorker->count = 4; // Emitted when new connection come $wsWorker->onConnect = function ($connection) { echo "New connection/n"; }; // Emitted when data received $wsWorker->onMessage = function ($connection, $data) { // Send hello $data $connection->send('hello ' . $data); }; // Emitted when connection closed $wsWorker->onClose = function ($connection) { echo "Connection closed/n"; };}
添加啟動(dòng)模塊
/** * workman websocket start */public function start(){ $this->initWorker(); // 重置參數(shù)以匹配Worker global $argv; $argv[0] = $argv[1]; $argv[1] = 'start'; if ($this->daemon) { $argv[2] = '-d'; } // Run worker Worker::runAll();}
添加停止模塊
/** * workman websocket stop */public function stop(){ $this->initWorker(); // 重置參數(shù)以匹配Worker global $argv; $argv[0] = $argv[1]; $argv[1] = 'stop'; if ($this->gracefully) { $argv[2] = '-g'; } // Run worker Worker::runAll();}
添加重啟模塊
/** * workman websocket restart */public function restart(){ $this->initWorker(); // 重置參數(shù)以匹配Worker global $argv; $argv[0] = $argv[1]; $argv[1] = 'restart'; if ($this->daemon) { $argv[2] = '-d'; } if ($this->gracefully) { $argv[2] = '-g'; } // Run worker Worker::runAll();}
添加重載模塊
新聞熱點(diǎn)
疑難解答
圖片精選