PHP+Swoole实现简单HTTP服务器

enable_static_handler 排除静态文件(排除后不会触发onRequest事件)
document_root 加载静态文件目录, 当有静态文件请求就会到此目录中寻找
worker_num 设置worker数量, worker是什么应该不用说了吧…
max_request 最大请求数, 当请求数超过设置的数值就会kill掉worker由Manager进程重启拉起新的worker, 主要是用来防止由于代码编写不当而产生的少量内存溢出问题(大量溢出怕是得好好检查代码了)

http = new \Swoole\Http\Server('0.0.0.0', 9501);
        $this->http->on('request', [$this, 'onRequest']);
        $this->http->set([
            'enable_static_handler' => true,
            'document_root'            => __DIR__ . '/public/static',
            'worker_num'                => 8,
            'max_request' 			     => 3000
        ]);
        $this->http->start();
    }

    public function onRequest($request, $response)
    {
        // 拒绝ico请求
        if($request->server['request_uri'] == '/favicon.ico') {
            $response->status(404);
            $response->end();
            return ;
        }

        $_POST = [];
        if (isset($request->post)) {
            foreach ($request->post as $key => $value) {
                $_POST[strtoupper($key)] = $value;
            }
        }
        $_GET = [];
        if (isset($request->get)) {
            foreach ($request->get as $key => $value) {
                $_GET[strtoupper($key)] = $value;
            }
        }
        $_SERVER = [];
        if (isset($request->server)) {
            foreach ($request->server as $key => $value) {
                $_SERVER[strtoupper($key)] = $value;
            }
        }
        if (isset($request->header)) {
            foreach ($request->header as $key => $value) {
                $_SERVER[strtoupper($key)] = $value;
            }
        }
        $_FILES = [];
        if (isset($request->files)) {
            foreach ($request->files as $key => $value) {
                $_FILES[strtoupper($key)] = $value;
            }
        }

        $pathInfo = $request->server['path_info'];

        // 处理path_info
        if ($pathInfo != '/') {
            if ($a = strrpos($pathInfo,'.')) {
                $pathInfo = substr($pathInfo, 0, $a-strlen($pathInfo));
            }
            $pathInfo = trim($pathInfo, '/');
            $pathInfo = explode('/', $pathInfo);

        }

        if (is_array($pathInfo)) {
            $model = $pathInfo[0] ?? 'Index';
            $controller = $pathInfo[1] ?? 'Index';
            $method = $pathInfo[2] ?? 'index';
        }
//
        $params = [];
        $classNme = "\\App\\Https\\{$model}\\Controllers\\{$controller}";
        try {
            ob_start();
            // 通过反射机制获取
            $class = (new ReflectionClass($classNme))->newInstanceArgs($params);
            $class->$method();
            $result = ob_get_contents();
            ob_end_clean();
            $response->header('Content-Type', 'text/html');
            $response->header('Charset', 'utf-8');
            $response->end($result);
        } catch (\Exception $e) {
        	// 调试 输出错误
            echo $e->getMessage();
        }

    }
}

你可能感兴趣的:(php,swoole,http)