swoole 异步http请求 协程调用 demo

这是一个PHP示例,展示如何使用Swoole库创建一个Http类来发起HTTP请求,包括GET和POST方法,并结合协程进行异步操作。示例中还包含了Task和Scheduler类,用于任务调度和管理。
摘要由CSDN通过智能技术生成
<?php
declare(strict_types=1);


/**
 * Class Http
 */
class Http
{
    private $sp = "\r\n"; //这里必须要写成双引号     private $protocol = 'HTTP/1.1';
    private $requestLine = "";
    private $requestHeader = "";
    private $requestInfo = "";
    private $fp = null;
    private $urlInfo = null;
    private $header = [];
    private $body = "";
    private static $http = null; //Http对象单例


    /**
     * Http constructor.
     */
    private function __construct()
    {
    }


    /**
     * @return Http|null
     */
    public static function getInstance()
    {
        if (self::$http === null) {
            self::$http = new Http();
        }
        return self::$http;
    }


    /**
     * @param $url
     * @return $this
     */
    public function init($url)
    {
        $this->parseUrl($url);
        $this->header['Host'] = $this->urlInfo['host'];
        return $this;
    }


    /**
     * @param array $header
     * @return Generator
     */
    public function get($header = []): Generator
    {
        $this->header = array_merge($this->header, $header);
        return $this->request('GET');
    }


    /**
     * @param array $header
     * @param array $body
     * @return bool
     */
    public function post($header = [], $body = [])
    {
        $this->header = array_merge($this->header, $header);
        if (!empty($body)) {
            $this->body = http_build_query($body);
            $this->header['Content-Type'] = 'application/x-www-form-urlencoded';
            $this->header['Content-Length'] = strlen($this->body);
        }
        return $this->request('POST');
    }


    /**
     * @param $method
     * @return bool
     */
    private function request($method)
    {
        $header = "";
        $this->requestLine = $method . ' ' . $this->urlInfo['path'] . '?' . $this->urlInfo['query'];
        foreach ($this->header as $key => $value) {
            $header .= $header == "" ? $key . ':' . $value : $this->sp . $key . ':' . $value;
        }
        $this->requestHeader = $header . $this->sp . $this->sp;
        $this->requestInfo = $this->requestLine . $this->sp . $this->requestHeader;
        if ($this->body != "") {
            $this->requestInfo .= $this->body;
        }
        $port = isset($this->urlInfo['port
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值