美文网首页
Swoole学习测试案例

Swoole学习测试案例

作者: 鸿雁长飞光不度 | 来源:发表于2018-09-30 21:41 被阅读0次
    class SwooleTest
    {
    
        private $host = "0.0.0.0";
    
        //tcp连接
        public function tcp()
        {
            $serv = new swoole_server($this->host, 9505);
            //监听连接进入事件
            $serv->on('connect', function ($serv, $fd) {
                echo "Client: Connect.\n";
            });
            //监听数据接收事件
            $serv->on('receive', function ($serv, $fd, $from_id, $data) {
                $serv->send($fd, "Server: " . $data);
            });
    
            //监听连接关闭事件
            $serv->on('close', function ($serv, $fd) {
                echo "Client: Close.\n";
            });
            //启动服务器
            $serv->start();
        }
        //http连接
        public function http()
        {
            $ser = new swoole_http_server($this->host, 9503);
            $ser->on('request', function ($request, $respond) {
                $respond->header("Content-Type", "text/html;charset=utf-8");
                $respond->end('hello world');
            });
            $ser->start();
        }
        //websocket
        public function websocket()
        {
            $server = new swoole_websocket_server("0.0.0.0", 9504);
            $server->on('open', function (swoole_websocket_server $server, $request) {
                echo "server: handshake success with fd{$request->fd}\n";
            });
            $server->on('message', function (swoole_websocket_server $server, $frame) {
                echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
                $server->push($frame->fd, "this is server");
            });
            $server->on('close', function ($ser, $fd) {
                echo "client {$fd} closed\n";
            });
            $server->on('open', function (swoole_websocket_server $ws, $request) {
                $ws->push($request->fd, 'welcome you');
            });
            $server->start();
    
        }
    
        //定时器间隔执行任务
        public function timer()
        {
            static $count = 0;
            swoole_timer_tick(2000, function ($timer_id) use (&$count) {
                if ($count == 3) {
                    swoole_timer_clear($timer_id);
                }
                $count++;
                echo '执行' . $count . "\n";
            });
    //        swoole_timer_after(1000,function($timer_id){
    //            echo '执行\n';
    //        });
        }
    
        //tcp异步执行任务
        public function asyncTcp()
        {
            $server = new swoole_server($this->host, 9502);
            //设置异步进程的工作数量
            $server->set(array(
                'task_worker_num' => 4
            ));
            //投递异步任务
            $server->on('receive', function (swoole_server $server, $fd, $from_id, $data) {
                $task_id = $server->task($data); //投递任务
            });
            //处理异步任务
            $server->on('task', function (swoole_server $server, $task_id, $from_id, $data) {
                echo "异步执行 ID :" . $task_id . "from_id:" . $from_id;
                $server->finish($data);
            });
            //处理结果
            $server->on('finish', function ($server, $task_id, $data) {
                echo "执行完成 task_id:$task_id,data:$data";
            });
            $server->start();
        }
    
    }
    
    
    class SwooleProcess{
    
        /**
        swoole_process提供了基于unixsock的进程间通信,使用很简单只需调用write/read或者push/pop即可
        swoole_process支持重定向标准输入和输出,在子进程内echo不会打印屏幕,而是写入管道,读键盘输入可以重定向为管道读取数据
        配合swoole_event模块,创建的PHP子进程可以异步的事件驱动模式
        swoole_process提供了exec接口,创建的进程可以执行其他程序,与原PHP父进程之间可以方便的通信
         */
        public function test() //创建进程
        {
            $process = new swoole_process([$this,"doProcess"]);
            $pid = $process->start();
            $process = new swoole_process([$this,"doProcess"]);
            $pid = $process->start();
            $process = new swoole_process([$this,"doProcess"]);
            $pid = $process->start();
    
            swoole_process::wait();
        }
    
        //进程间管道通信
        public function pipe()
        {
            $workers = [];
            $worker_num = 3;
            for ($i = 0; $i < $worker_num; $i++){
                $process = new swoole_process([$this,"doProcess2"]);
                $pid = $process->start();
                $workers[$pid] = $process;
            }
    
            foreach ($workers as $worker){
                swoole_event_add($worker->pipe,function($pipe) use ($worker){
                   $data = $worker->read();
                   echo "接收到数据".$data."\n";
                });
            }
        }
    
        function doProcess2(swoole_process $worker)
        {
            $worker->write("PID:".$worker->pid); //子进程向管道写入信息z
        }
        function doProcess(swoole_process $worker)
        {
            echo "PID".$worker->pid."\n";
        }
    
        /**
         * 进程每隔一段时间异步的触发一个函数
         */
        public function signal()
        {
            //触发函数
            swoole_process::signal(SIGALRM,function (){ //异步执行,10次停止
                static $times = 1;
                if ($times == 10){
                    swoole_process::alarm(-1);
                }
                echo $times++;
            });
            swoole_process::alarm(100* 1000); //代码不提示
            //定时信号
        }
    }
    
    class Lock
    {
        /**
         * 测试失败,有时间了需要重新安装扩展
         *
         */
        public function test()
        {
            //文件锁/读写锁/互斥锁/信号量/自旋锁 --- 查
            $lock = new swoole_lock(SWOOLE_MUTEX);
            $lock->lock(); //开始锁定进程
            if (pcntl_fork() > 0){ //创建子进程
                sleep(1);
                $lock->unlock();
            }else{
                echo "子进程获取锁";
                $lock->lock();
                echo "子进程获取锁";
                $lock->unlock();
                exit("子进程退出");
            }
            echo "主进程释放锁";
            unset($lock);
            sleep(1);
            echo "子进程退出";
        }
    }
    
    /**
     * 异步IO
     * Class SwooleAsyncFile
     */
    class SwooleAsyncIO{
    
        public function test()
        {
            //文件异步读取
            swoole_async_readfile('test.txt',function ($filename,$content){
                echo $content;
            });
            //最大4M,异步写入文件
            swoole_async_writefile('test.txt',"需要写入的文件内容",function($filename){
                echo $filename;
            },FILE_APPEND);
        }
    
        //异步事件,异步的从www.qq.com获取内容
        public function test2()
        {
            $fp = stream_socket_client("tcp://www.qq.com:80",$error,$errstr,30);
            fwrite($fp,"GET / HTTP/1.1 \r\nHost:www.qq.com\r\n\r\n"); //用tcp连接发起http请求
            swoole_event_add($fp,function($fp){
                $resp = fread($fp,8192);
                var_dump($resp);
                swoole_event_del($fp); //删除任务
                fclose($fp);
            });
        }
    
        //异步mysql操作
        public function test3()
        {
            $config = [
                'host' => '127.0.0.1',
                'user' => 'root',
                'password' => '123456',
                'database' => 'mysql',
                'charset' => 'utf8'
            ];
            $db = new swoole_mysql();
            $db->connect($config,function(swoole_mysql $db,$r){
               if ($r === false){
                   var_dump($db->connect_errno,$db->connect_error);
                   die('失败');
               }
               $sql = 'show tables';
               $db->query($sql,function(swoole_mysql $db, $r){
                  if ($r === false){
                      var_dump($db->error);
                      die('操作失败');
                  }elseif ($r === true){
                      var_dump($db->affected_rows,$db->insert_id);
                  }
               });
            });
        }
    }
    

    相关文章

      网友评论

          本文标题:Swoole学习测试案例

          本文链接:https://www.haomeiwen.com/subject/bllgoftx.html