旗下导航:搜·么
当前位置:网站首页 > PHP教程 > 正文

swoole_process父子历程管道通讯的代码示例【php教程】

作者:搜搜PHP网发布时间:2019-11-26分类:PHP教程浏览:89


导读:本篇文章给人人带来的内容是关于swoole_process父子历程管道通讯的代码示例,有肯定的参考价值,有须要的朋侪能够参考一下,愿望对你有所协助。话不多说直接上代码建立的...

本篇文章给人人带来的内容是关于swoole_process父子历程管道通讯的代码示例,有肯定的参考价值,有须要的朋侪能够参考一下,愿望对你有所协助。

话不多说直接上代码

建立的子历程:

public function __construct()
    {
        $this->redis   = Container::get(SwooleRedis::class);//猎取异步redis猎取更高机能
        $this->process = new swoole_process(function (swoole_process $process) {
            return $this->process($process);
        }, false, SOCK_DGRAM);
        $this->process->name('Test_Gateway');
        $this->process->useQueue();
        $this->process->start();//启动子历程
    }
    
    /**
     * 子历程处置惩罚逻辑
     * @param swoole_process $process
     */
    private function process(swoole_process $process)
    {
        $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非壅塞
        
        $client->on("connect", function (swoole_client $cli) use ($process) {
            $process->write('connected');
        });
        
        $client->on("receive", function (swoole_client $cli, $data) use ($process) {
            $process->write($data);
        });
        
        $client->on("error", function (swoole_client $cli) use ($process) {
            $process->write('error');
        });
        
        $client->on("close", function (swoole_client $cli) use ($process) {
            $process->write('close');
        });
        
        if ($client->connect('127.0.0.1', 90, -1)) {
        
        } else {
            $process->write('网关衔接失利');
        }
        
        swoole_event_add($process->pipe,
            function ($pipe) use ($process, $client) {//读取父历程管道音讯
                $client->send($process->read());
            });
    }

父历程onWorkerStart:

/**
     * @param swoole_server $serv
     * @param               $worker_id
     */
    public function onWorkerStart(\swoole_server $serv, $worker_id)
    {
        if ($worker_id === 0) {
            swoole_timer_tick(1000, function () {
                $this->process->write('ping');
            });
            $process = $this->process;
            swoole_event_add($process->pipe,
                function ($pipe) use ($process) {//猎取子历程的管道音讯
                    echo "子历程音讯:" . $process->read() . PHP_EOL;
                });
        }
    }
  • 子历程的client客户端能够忽略不计,本demo只是掩盖管道通讯的例子
  • 运用管道就不能够运用音讯行列:$process_push()和$process->pop();
  • 理论上在父子历程各注册一个event_loop即可完成一边发音讯一边吸收
  • 其他的后续补充

以上就是swoole_process父子历程管道通讯的代码示例的细致内容,更多请关注ki4网别的相干文章!

标签:phpswoole