为什么要自定义命令 tp6 作者已经明确提出,php客户端不支持访问类 ,所以想用客户端访问php只能是用自定义命令,也很简单!
创建自定义命令
php think make:command Swoole tcp
代码如下
<?php
declare (strict_types = 1);
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class Swoole extends Command
{
protected function configure()
{
// 指令配置
$this->setName('tcp')
->setDescription('the tcp command');
}
protected function execute(Input $input, Output $output)
{
//创建Server对象,监听 0.0.0.0:9501端口
$serv = new \Swoole\Server("0.0.0.0", 9501);
//监听连接进入事件
$serv->on('Connect', function ($serv, $fd) {
echo "与客户端已经建立连接: .\n";
});
//监听数据接收事件
$serv->on('Receive', function ($serv, $fd, $from_id, $data) {
$serv->send($fd, "服务器发送消息: ".$data);
});
//监听连接关闭事件
$serv->on('Close', function ($serv, $fd) {
echo "客户端关闭: Close.\n";
});
//启动服务器
$serv->start();
// 指令输出
$output->writeln('tcp');
}
}
在config下的console.php配置文件添加
return [
// 指令定义
'commands' => [
'swoole_tcp' => 'app\command\Swoole',
],
];
命令行启行 执行该命令
php think swoole_tcp
tcp客户端 (乱码 是服务器中文字符 ,编码不一致所致,可以忽略)
成功运行自定义命令的 swoole-tcp服务