swoole实现一个web http、https代理服务器代码

代码语言:phpcli

所属分类:通讯

代码描述:swoole实现一个web http、https代理服务器代码

代码标签: swoole web http https 代理 服务器 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?php
/**
 * Web代理服务器(支持http/https)
 * 支持php5.6下运行通过
 */
class WebProxyServer
{
    private $_client = [];
    private $_server;

    /**
     * 日志打印
     * @author auther
     * @param string $message
     */
    protected function log($message)
    {
        echo $message . PHP_EOL;
    }

    /**
     * 获取代理ip
     * @author auther
     */
    protected function getLocalIp()
    {
        //获取代理IP
        $ipList = swoole_get_local_ip();
        foreach($ipList as $interface => $ip) {
            $this->log("{$interface}:{$ip}");
        }
    }

    /**
     * 初始化
     * @author auther
     */
    protected function init()
    {
        //$this->getLocalIp();

        $this->_server = new swoole_server("0.0.0.0", 8889);

        $this->_server->set([
            'buffer_output_size' => 64 * 1024 *1024, //必须为数字
        ]);
    }

    /**
     * 跑起来
     * @author auther
     */
    public function run()
    {
        $this->init();

        $this->_server->on('connect', function ($server, $fd){
            $this->log("Server connection open: {$fd}");
        });

        $this->_server->on('receive', function ($server, $fd, $reactor_id, $buffer){

            //判断是否为新连接
            if(!isset($this->_client[$fd])) {
                //判断代理模式
                list($method, $url) = explode(' ', $buffer, 3);
                $url = parse_url($url);

                //ipv6为啥外面还有个方括号?
                if(strpos($url['host'], ']')) {
                    $url['host'] = str_replace(['[', ']'], '', $url['host']);
                }

                //解析host+port
                $host = $url['host'];
                $port = isset($url['port']) ? $url['port'] : 80;

                //ipv4/v6处理
                $tcpMode = strpos($url['host'], ':') !== false ? SWOOLE_SOCK_TCP6 : SWOOLE_SOCK_TCP;
                $this->_client[$fd] = new swoole_client($tcpMode, SWOOLE_SOCK_ASYNC);

                if($method == 'CONNECT')
                {
   .........完整代码请登录后点击上方下载按钮下载查看

网友评论0