💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
在很多情况下,大家使用 Swoole 都只是在使用 web socket,而没有使用 Swoole 真正“重新定义PHP”的功能,那么 Swoole 真正解决了 PHP 的痛点就是本章介绍的,仅仅使用 web socket 还没体现出 Swoole 真正的高性能方面。 我们通常使用 Nginx,Apache 或者 IIS 来做为运行 PHP 的 Web 服务器,其实是内部的 PHP 解析器来解析 PHP 代码,PHP 内部提供了 SAPI(Server Application Programming Interface/服务器端应用编程端口)来跟外部程序(Apache,Nginx等)通信。比如 Nginx 常用的 phpfpm,Apache 常用的 mod_php,命令行的 CLI 以及 IIS 常用的ISAPI。 常用的 Web 服务器中,Nginx + phpfpm 这个组合在性能方面表现格外出色,但是我们现在可以通过 Swoole 来自己实现一个应用服务器,性能要比 phpfpm 还要好,在 Swoole 官方压力测试中,swoole_http_server(Swoole 实现的 http 服务器)要比 phpfpm 性能好很多,甚至很接近 Nginx 处理静态资源文件。但是不推荐只使用 swoole_http_server 来作为 Web 服务器,推荐和 Nginx 搭配使用,由 swoole_http_server 来替代 phpfpm 处理 php 解析,静态资源文件依然由 Nginx 来处理。 swoole_http_server 是基于 swoole_server 的基础上增加 http 协议的解析,所有的 http 请求会在解析后封装到 swoole_http_request 对象内,所有 http 响应也会封装到 swoole_http_response 对象内并发送。需要注意的是在 swoole_http_server 中,普通的$_POST,$_GET,$_REQUEST,$_SERVER等全局变量还有echo等都不能使用 暂未实现直接用 swoole_http_server 替代框架入口文件,所以本章示例是用 swoole_http_server 实现后,适用在 html 层用 ajax 调用 创建 ThinkPHP5 自定义命令行 1.创建命令行类 - 创建application/console/HttpServer.php文件 ~~~ <?php namespace app\Console; use think\console\Command; use think\console\Input; use think\console\Output; class HttpServer extends Command { protected $server; // 命令行配置函数 protected function configure() { // setName 设置命令行名称 && setDescription 设置命令行描述 $this->setName('http:server')->setDescription('Start Http Server!'); } // 设置命令返回信息 protected function execute(Input $input, Output $output) { $this->server = new \swoole_http_server("0.0.0.0", 9502); $this->server->on('Request', [$this, 'onRequest']); $this->server->start(); // $output->writeln("HttpServer: Start.\n"); } public function onRequest(\swoole_http_request $request, \swoole_http_response $response) { $data = isset($request->get) ? $request->get : ''; $response->end(serialize($data)); } } ~~~ 2.修改配置文件 - 文件所在 application/command.php ~~~ <?php return [ 'app\console\HttpServer', ]; ~~~ 这时直接在命令行输入如下命令就可以启动 swoole_http_server 1 $ > `php think http:server` 这时候在浏览器打开连接,使用 get 传递参数,浏览器页面会直接显示序列化后的 get 参数 ![](https://box.kancloud.cn/a238e534b225e393b2446f2cb2771a89_543x115.png)