tp5都有的自定义指令在tp6文档没有找到。根据之前的tp5的也差不多一样的用法

  1. php think make:command Swoole tcp

QQ截图20200709201636

如上图指令类就创建好了

  1. <?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)
       {
           $this->server = new \swoole_server('0.0.0.0', 9501);

           $this->server->set([
               'worker_num' => 4,
               'daemonize'  => false,
           ]);

           $this->server->on('Start', [$this, 'onStart']);
           $this->server->on('Connect', [$this, 'onConnect']);
           $this->server->on('Receive', [$this, 'onReceive']);
           $this->server->on('Close', [$this, 'onClose']);

           $this->server->start();
        // 指令输出
        $output->writeln('tcp');
       }

       // 主进程启动时回调函数
       public function onStart(\swoole_server $serv)
       {
           echo "Start\n";
       }

       // 建立连接时回调函数
       public function onConnect(\swoole_server $server, $fd, $from_id)
       {
           echo "Connect\n";
       }

       // 收到信息时回调函数
       public function onReceive(\swoole_server $server, $fd, $from_id, $data)
       {
           echo "message: {$dataform Client: {$fd\n";
           // 将受到的客户端消息再返回给客户端
           $server->send($fd, "Message form Server: ".$data);
       }

       // 关闭连时回调函数
       public function onClose(\swoole_server $server, $fd, $from_id)
       {
           echo "Close\n";
       }

    }

在config目录下有个console.php指令配置文件 如下


  1. return [
       // 指令定义
       'commands' => [
           'swoole_tcp' => 'app\command\Swoole',
       ],
    ];

跟目录命令行执行

  1. 执行
    php think

    Available commands:
     clear             Clear runtime file
     help              Displays help for a command
     list              Lists commands
     run               PHP Built-in Server for ThinkPHP
     swoole            Swoole HTTP Server for ThinkPHP
     swoole_tcp        the tcp command   //这里有表示成功如果这里没有表示没添加成功
     version           show thinkphp framework version


  1. php think swoole_tcp

rutu

支持控制器调用指令,例如:

  1. <?php
    namespace app\index\controller;

    use think\facade\Console;

    class Index
    {
       public function hello($name)
       {
           $output = Console::call('hello', [$name]);

           return $output->fetch();
       }
    }

访问该方法后

  1. http://tp5.com/index/hello/name/thinkphp

    输出:
    Hello thinkphp!
相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!