由于workerman底层直接读取$_SERVER['argv']的命令行参数,没有提供独立的方法start/stop,而tp的命令行参数无法适配workerman,虽然thinkphp官方专门做了一个适配的版本,但是看了下评论问题挺多的。于是自己来搞一个.
(1).在application/command.php中添加如下代码:
return [ 'app\socket\command\Socket' ];
(2).创建 application/socket/command目录,在这个目录创建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 { /** * 命令Input配置 */ protected function configure() { $this->setName('socket') ->addArgument('action', Argument::OPTIONAL, "action") ->addOption('other', '-d', Option::VALUE_OPTIONAL, 'test'); } /** * 重置Cli参数 */ 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; } /** * 命令响应 * @param Input $input * @param Output $output * @return int|void|null */ protected function execute(Input $input, Output $output) { //01.重置Cli命令行参数 $this->resetCli(); //02.开始WorkMan代码 $ws_worker = new Worker(config('socket.socket_name')); // 启动4个进程对外提供服务 $ws_worker->count = 2; // 接收到浏览器发送的数据时回复hello world给浏览器 $ws_worker->onMessage = function ($connection, $data) { // 向浏览器发送hello world $connection->send('hello ' . $data); }; // 运行worker Worker::runAll(); } }
(3).在tp根目录执行命令
php think socket start
名字不想叫socket,可以修改$this->setName('socket')
<!doctype html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <bod...
应用场景:PHP模拟购买,商品数量大于0才能购买常见代码:<?php //连接数据库 $con=mysqli_connect("localhost","ihuohuo","927464cy","ihuohuo");...
php官方的超全局变量$_SERVER['PHP_SELF']也能直接获取,只不过如果url参数太多也会获取。下面提供一个方法获取/* * 获取当前PHP文件名称 */ if (!function_exists('phpself...
使用php函数array_multisort()即可实现和SQL一样的order by排序. 例如我们需要对会员表按照主键降序排列,年龄升序排列://会员表数据 $list = []; $list[] = ['mid' =>&n...
php arrayaccess 官方的说法是让你能以数组的形式访问对象,对于这种php内置接口一直不太明白有什么用,坚持多看文章,终于理解,特来分享,思路不同,更易于理解。(1).创建一个学生类,并且实现arrayaccess 接口。<?php class studen...
最近在公司开发一个新的项目假设项目域名是a.com,需要接入b.com的单点登陆系统。(1).首先我们会在a.com的登陆页面用iframe引入b.com来显示登陆界面,实际上登陆验证操作都是在b.com上面(2).当b.com验证通过,会在前端ajax请求a.com的回调地址,这个回调地址目的就是...