zoukankan      html  css  js  c++  java
  • thinkphp5 swoole 执行异步任务

    目录结构:

    服务器端:

    <?php
    /*
    *author:hdj
    */
    namespace appConsole;
    use thinkconsoleCommand;
    use thinkconsoleInput;
    use thinkconsoleOutput;
    
    class Websocket extends Command{
        protected $server;
        protected function configure()
        {
           $this->setName('websocket:start')->setDescription('Start Web Socket Server!');
        }
        protected function execute(Input $input, Output $output)
        {
            $serv = new swoole_server('0.0.0.0',9501);
    
            $serv->set(array('task_worker_num' => 4));
    
            $serv->on('connect', function ($serv, $fd){
                echo $fd."客户端已经连接进来了.
    ";
            });
            $serv->on('receive', function($serv, $fd, $from_id, $data) {
                $task_id = $serv->task($data);
                echo "开始投递异步任务 id=$task_id
    ";
            });
    
            $serv->on('task', function ($serv, $task_id, $from_id, $data) {
                echo "接收异步任务[id=$task_id]".PHP_EOL;
                for ($i = 0 ; $i<10000;$i++){
                    if($i%2==0){
                        echo 'send'.$i.' success'."
    ";
                    }else{
                        echo 'send'.$i.' fail'."
    ";
                    }
                    sleep(1);
                }
    
                $serv->finish("$data -> OK");
            });
    
            $serv->on('finish', function ($serv, $task_id, $data) {
                echo "异步任务[id=$task_id]完成".PHP_EOL;
            });
            $serv->start();
        }
    }

    进入你的根目录 执行  php think websocket:start

    客户端:

    <?php
    namespace appindexcontroller;
    use thinkController;
    class Test extends Controller
    {
      public function index(){
          $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
          $ret = $client->connect("23.27.127.32", 9501);
          if(empty($ret)){
              echo 'error!connect to swoole_server failed';
          } else {
              $client->send('blue');
          }
      }
    
    }

    服务端显示:

  • 相关阅读:
    jQuery的几个Grid插件简单比较
    位运算符
    Unity --- 纹理压缩基本知识点
    Unity---资源管理中不同资源的路径获取方式
    Unity--- 资源路径问题
    数据结构 --- 基本概念
    《UnityShader入门精要》学习笔记之渲染流水线
    UnityShader中的语义相关
    补充一下角度制与弧度制的相关知识
    NGUI中处理层级问题的几个方法总结
  • 原文地址:https://www.cnblogs.com/houdj/p/7730147.html
Copyright © 2011-2022 走看看