介紹 Swoole HTTP的應用
推荐(免费):Swoole
概述
我们都知道HTTP是一种协议,允许WEB服务器和浏览器通过互联网进行发送和接受数据。
想对HTTP进行详细的了解,可以找下其他文章,这篇文章不多做介绍。
我们在网上能看到的界面,图片,动画,音频,视频等,都有依赖这个协议的。
在做WEB系统的时候,都使用过IIS,Apache,Nginx吧,我们利用Swoole也可以简单的实现一个WEB服务器。
主要使用了HTTP的两个大对象:Request请求对象,Response响应对象。
请求,包括GET,POST,COOKIE,Header等。
响应,包括状态,响应体,扩展,发送文件等。
不多说,先分享两个程序:
一,实现一个基础的Demo:“你好,Swoole。”
二,实现一个简单的路由控制
本地版本:
PHP 7.2.6
旋风4.3.1
代码
一,Demo:“你好,Swoole。”
示例效果:
备注:IP地址是我的虚拟机。
示例代码:
<?php class Server { private $serv; public function __construct() { $this->serv = new swoole_http_server("0.0.0.0", 9502); $this->serv->set([ 'worker_num' => 2, //开启2个worker进程 'max_request' => 4, //每个worker进程 max_request设置为4次 'daemonize' => false, //守护进程(true/false) ]); $this->serv->on('Start', [$this, 'onStart']); $this->serv->on('WorkerStart', [$this, 'onWorkStart']); $this->serv->on('ManagerStart', [$this, 'onManagerStart']); $this->serv->on("Request", [$this, 'onRequest']); $this->serv->start(); } public function onStart($serv) { echo "#### onStart ####".PHP_EOL; echo "SWOOLE ".SWOOLE_VERSION . " 服务已启动".PHP_EOL; echo "master_pid: {$serv->master_pid}".PHP_EOL; echo "manager_pid: {$serv->manager_pid}".PHP_EOL; echo "########".PHP_EOL.PHP_EOL; } public function onManagerStart($serv) { echo "#### onManagerStart ####".PHP_EOL.PHP_EOL; } public function onWorkStart($serv, $worker_id) { echo "#### onWorkStart ####".PHP_EOL.PHP_EOL; } public function onRequest($request, $response) { $response->header("Content-Type", "text/html; charset=utf-8"); $html = "<h1>你好 Swoole.</h1>"; $response->end($html); } } $server = new Server();
二,路由控制
示例效果:
目录结构:
├─ swoole_http -- 代码根目录 │ ├─ server.php │ ├─ controller │ ├── Index.php │ ├── Login.php
示例代码:
server.php
<?php class Server { private $serv; public function __construct() { $this->serv = new swoole_http_server("0.0.0.0", 9501); $this->serv->set([ 'worker_num' => 2, //开启2个worker进程 'max_request' => 4, //每个worker进程 max_request设置为4次 'document_root' => '', 'enable_static_handler' => true, 'daemonize' => false, //守护进程(true/false) ]); $this->serv->on('Start', [$this, 'onStart']); $this->serv->on('WorkerStart', [$this, 'onWorkStart']); $this->serv->on('ManagerStart', [$this, 'onManagerStart']); $this->serv->on("Request", [$this, 'onRequest']); $this->serv->start(); } public function onStart($serv) { echo "#### onStart ####".PHP_EOL; swoole_set_process_name('swoole_process_server_master'); echo "SWOOLE ".SWOOLE_VERSION . " 服务已启动".PHP_EOL; echo "master_pid: {$serv->master_pid}".PHP_EOL; echo "manager_pid: {$serv->manager_pid}".PHP_EOL; echo "########".PHP_EOL.PHP_EOL; } public function onManagerStart($serv) { echo "#### onManagerStart ####".PHP_EOL.PHP_EOL; swoole_set_process_name('swoole_process_server_manager'); } public function onWorkStart($serv, $worker_id) { echo "#### onWorkStart ####".PHP_EOL.PHP_EOL; swoole_set_process_name('swoole_process_server_worker'); spl_autoload_register(function ($className) { $classPath = __DIR__ . "/controller/" . $className . ".php"; if (is_file($classPath)) { require "{$classPath}"; return; } }); } public function onRequest($request, $response) { $response->header("Server", "SwooleServer"); $response->header("Content-Type", "text/html; charset=utf-8"); $server = $request->server; $path_info = $server['path_info']; $request_uri = $server['request_uri']; if ($path_info == '/favicon.ico' || $request_uri == '/favicon.ico') { return $response->end(); } $controller = 'Index'; $method = 'home'; if ($path_info != '/') { $path_info = explode('/',$path_info); if (!is_array($path_info)) { $response->status(404); $response->end('URL不存在'); } if ($path_info[1] == 'favicon.ico') { return; } $count_path_info = count($path_info); if ($count_path_info > 4) { $response->status(404); $response->end('URL不存在'); } $controller = (isset($path_info[1]) && !empty($path_info[1])) ? $path_info[1] : $controller; $method = (isset($path_info[2]) && !empty($path_info[2])) ? $path_info[2] : $method; } $result = "class 不存在"; if (class_exists($controller)) { $class = new $controller(); $result = "method 不存在"; if (method_exists($controller, $method)) { $result = $class->$method($request); } } $response->end($result); } } $server = new Server();
Index.php
<?php class Index { public function home($request) { $get = isset($request->get) ? $request->get : []; //@TODO 业务代码 $result = "<h1>你好,Swoole。</h1>"; $result.= "GET参数:".json_encode($get); return $result; } }
Login.php
<?php class Login { public function index($request) { $post = isset($request->post) ? $request->post : []; //@TODO 业务代码 return "<h1>登录成功。</h1>"; } }
小结
一,Swoole可以替代Nginx吗?
暂时不能,通过Swoole越来越强大,以后说不准。
官方建议Swoole与Nginx结合使用。
Http \ Server对Http协议的支持并不完整,建议仅作为应用服务器。并且在前端增加Nginx作为代理。
根据自己的Nginx配置文件,可以自行调整。
例如:可以添加一个配置文件
enable-swoole-php.conf
location ~ [^/]\.php(/|$) { proxy_http_version 1.1; proxy_set_header Connection "keep-alive"; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://127.0.0.1:9501; }
我们都习惯于将虚拟域名的配置文件放在vhost文件夹中。
例如,虚拟域名的配置文件为:local.swoole.com.conf,可以选择加载enable-php.conf,也可以选择加载enable-swoole-php.conf。
配置文件供参考:
server { listen 80; #listen [::]:80; server_name local.swoole.com ; index index.html index.htm index.php default.html default.htm default.php; root /home/wwwroot/project/swoole; #include rewrite/none.conf; #error_page 404 /404.html; #include enable-php.conf; include enable-swoole-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /.well-known { allow all; } location ~ /\. { deny all; } access_log /home/wwwlogs/local.swoole.com.log; }
当前,我们直接编辑server段的代码也是可以的。
二,修改了controller文件夹中的业务代码,每次都是重启服务才生效吗?
不是,每次重启服务可能会影响到正常用户使用的,正常处理的请求会被强制关闭。
在本地运行路由控制的代码时,试试这个命令:
ps aux | grep swoole_process_server_master | awk '{print $2}' | xargs kill -USR1
给master进程发送一个USR1的信号,当Swoole Server接收到该信号后,就会让所有worker在处理完当前的请求后,进行重启。
如果查看所有的进程,试试这个命令:
ps -ef | grep 'swoole_process_server'| grep -v 'grep'
扩展
可以试着上传文件,做一个小的FTP服务器。
可以学习Swoole开源框架:EasySwoole,Swoft,One。
-
可以将Swoole整合到当前正在使用的PHP框架中。
更多相关精品文章敬请关注swoole框架栏目!
以上是介紹 Swoole HTTP的應用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Laravel 中使用 Swoole 協程可以並發處理大量請求,優點包括:同時處理:允許同時處理多個請求。高效能:基於 Linux epoll 事件機制,高效處理請求。低資源消耗:所需伺服器資源更少。易於整合:與 Laravel 框架無縫集成,使用簡單。

掌握HTTP301狀態碼的意思:網頁重定向的常見應用場景隨著網路的快速發展,人們對網頁互動的要求也越來越高。在網頁設計領域,網頁重定向是一種常見且重要的技術,透過HTTP301狀態碼來實現。本文將探討HTTP301狀態碼的意義以及在網頁重新導向中的常見應用場景。 HTTP301狀態碼是指永久重新導向(PermanentRedirect)。當伺服器接收到客戶端發

HTTP狀態碼200:探索成功回應的意義與用途HTTP狀態碼是用來表示伺服器回應狀態的數字代碼。其中,狀態碼200表示請求已成功被伺服器處理。本文將探討HTTP狀態碼200的具體意義與用途。首先,讓我們來了解HTTP狀態碼的分類。狀態碼分為五個類別,分別是1xx、2xx、3xx、4xx和5xx。其中,2xx表示成功的回應。而200是2xx中最常見的狀態碼

若要重新啟動 Swoole 服務,請依照下列步驟操作:檢查服務狀態並取得 PID。使用 "kill -15 PID" 停止服務。使用啟動服務的相同命令重新啟動服務。

Swoole 和 Workerman 都是高效能 PHP 伺服器框架。 Swoole 以其非同步處理、出色的效能和可擴展性而聞名,適用於需要處理大量並發請求和高吞吐量的專案。 Workerman 提供了非同步和同步模式的靈活性,具有直覺的 API,更適合易用性和處理較低並發量的專案。

效能比較:吞吐量:Swoole 以協程機制,吞吐量更高。延遲:Swoole 的協程上下文切換開銷更低,延遲更小。記憶體消耗:Swoole 的協程佔用記憶體較少。易用性:Swoole 提供更易於使用的並發程式設計 API。

解決方法:1、檢查請求頭中的Content-Type;2、檢查請求體中的資料格式;3、使用適當的編碼格式;4、使用適當的請求方法;5、檢查伺服器端的支援。
