由于workerman底層直接讀取$_SERVER['argv']的命令行參數(shù),沒有提供獨(dú)立的方法start/stop,而tp的命令行參數(shù)無法適配workerman,雖然thinkphp官方專門做了一個(gè)適配的版本,但是看了下評(píng)論問題挺多的。于是自己來搞一個(gè).
(1).在application/command.php中添加如下代碼:
return [
'app\socket\command\Socket'
];
(2).創(chuàng)建 application/socket/command目錄,在這個(gè)目錄創(chuàng)建Socket.php文件
<?php
namespace app\socket\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Worker;
class Socket extends Command
{
/**
* 命令I(lǐng)nput配置
*/
protected function configure()
{
$this->setName('socket')
->addArgument('action', Argument::OPTIONAL, "action")
->addOption('other', '-d', Option::VALUE_OPTIONAL, 'test');
}
/**
* 重置Cli參數(shù)
*/
protected function resetCli()
{
global $argv, $argc;
$file = "{$argv['0']} {$argv['1']}";
$action = $argv['2'];
$extend = empty($argv['3']) ? '' : $argv['3'];
$argv = [];
$argv[] = $file;
$argv[] = $action;
if ($extend)
{
$argv[] = $extend;
}
$argc = count($argv);
$_SERVER['argv'] = $argv;
$_SERVER['argc'] = $argc;
}
/**
* 命令響應(yīng)
* @param Input $input
* @param Output $output
* @return int|void|null
*/
protected function execute(Input $input, Output $output)
{
//01.重置Cli命令行參數(shù)
$this->resetCli();
//02.開始WorkMan代碼
$ws_worker = new Worker(config('socket.socket_name'));
// 啟動(dòng)4個(gè)進(jìn)程對(duì)外提供服務(wù)
$ws_worker->count = 2;
// 接收到瀏覽器發(fā)送的數(shù)據(jù)時(shí)回復(fù)hello world給瀏覽器
$ws_worker->onMessage = function ($connection, $data) {
// 向?yàn)g覽器發(fā)送hello world
$connection->send('hello ' . $data);
};
// 運(yùn)行worker
Worker::runAll();
}
}
(3).在tp根目錄執(zhí)行命令
php think socket start
名字不想叫socket,可以修改$this->setName('socket')
linux和windows全部支持。甚至兼容了workerman的提示命令都是提示正確的
Input "php think socket stop" to stop. Start success.
stop輸出:
Workerman[think socket] stop
Workerman[think socket] is stopping ...
Workerman[think socket] stop success
完美