Swoole HTTP 的应用
概述
这是关于 Swoole 学习的第四篇文章:Swoole HTTP 的应用。
我们都知道 HTTP 是一种协议,允许 WEB 服务器和浏览器通过互联网进行发送和接受数据。
想对 HTTP 进行详细的了解,可以找下其他文章。
我们在网上能看到的界面,图片,动画,音频,视频 等,都有依赖这个协议的。
在做 WEB 系统的时候,都使用过 IIS、Apache、Nginx 吧,我们利用 Swoole 也可以 简单的实现一个 WEB 服务器。
主要使用了 HTTP 的两大对象:Request 请求对象、Response 响应对象。
Request,包括 GET、POST、COOKIE、Header等。
Response,包括 状态、响应体、跳转、发送文件等。
不多说,分享两个程序:
- 一、实现一个基础的 Demo:“你好,Swoole.”
- 二、实现一个简单的 路由控制
本地版本:
- PHP 7.2.6
- Swoole 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'
需要文章中源码的,关注公众号,回复“swoole http”即可。
扩展
- 可以试着上传文件,做一个小的FTP服务器。
- 可以试着整合到目前正在使用的PHP框架中。
- 可以学习一些Swoole开源框架:EasySwoole、Swoft、One。
本文欢迎转发,转发请注明作者和出处,谢谢!
Swoole HTTP 的应用的更多相关文章
- 编译安装PHP7并安装Redis扩展Swoole扩展
编译安装PHP7并安装Redis扩展Swoole扩展 在编译php7的机器上已经有编译安装过php5.3以上的版本,从而依赖库都有了 本php7是编译成fpm-php 使用的, 如果是apache那么 ...
- 使用php+swoole对client数据实时更新(下)
上一篇提到了swoole的基本使用,现在通过几行基本的语句来实现比较复杂的逻辑操作: 先说一下业务场景.我们目前的大多数应用都是以服务端+接口+客户端的方式去协调工作的,这样的好处在于不论是处在何种终 ...
- 使用php+swoole对client数据实时更新(上)
如果想对一个列表做实时的更新,传统的做法是采用轮询的方式.以web为例,通过Ajax定时请求服务端然后获取数据显示在页面.这种方式实现简单,缺点就是浪费资源. HTTP1.1新增加了对websocke ...
- [Linux][PHP]安装swoole扩展
1.下载swoole 2.解压并配置 /usr/local/php/bin/phpize ./configure --enable-swoole-debug --enable-sockets --en ...
- 被swoole坑哭的PHP程序员
被swoole坑哭的PHP程序员 2015-09-16 09:57 文帅营 博客园 字号:T | T 首先说一下对swoole的理解:披着PHP外衣的C程序.很多PHPer朋友看到swoole提供的强 ...
- centos下php安装swoole扩展
官网:http://wiki.swoole.com/wiki/index/prid-1 国内Git镜像:http://git.oschina.net/matyhtf/swoole.git 下载源码后, ...
- windows php swoole 安装
Cygwin 官方地址:http://www.cygwin.com/ swoole 官方下载地址:https://github.com/swoole/swoole-src/releases 1.下载 ...
- Linux下swoole的安装配置
前几天搭建swoole环境,在安装php的swoole扩展时不知道什么原因,提示成功,但是使用的时候不能加载,最后决定重新安装php试试,顺便记录了php的安装过程 wget http://cn2.p ...
- 简单的聊天室代码php+swoole
php swoole+websocket 客户端代码 <!DOCTYPE html> <html> <head> <title></title&g ...
- swoole 使用 1
在很长的一段时间里,我不太看好swoole,发现它的文档太少,社区也不够活跃等,但是最近在学习 Hprose时,发现swoole在rpc方面做得更加完善,于是决定看看. 在简单的使用swoole扩展后 ...
随机推荐
- display:inline
一.基本介绍 它可以让行内显示为块的元素,变为行内显示,例如 <div> DIV1 </div> <div> DIV2 </div> 这里DIV1和DI ...
- Contiki Ctimer模块
Ctimer 提供和Etimer类似的功能,只是Ctimer是在一段时间后调用回调函数,没有和特定进程相关联. 而Etimer是在一段时间后发送PROCESS_EVENT_TIMER事件给特定的进程. ...
- Kafka kafka.common.OffsetOutOfRangeException 问题处理
最近公司的zk的down掉了, storm job 重启的时候报出 kafka.common.OffsetOutOfRangeException 异常 网上查询了一些朋友的做法, 自己也看了一下代码 ...
- JAVA- 清除数组重复元素
清除数组重复元素并打印新数组. import java.util.*; public class Repeat { public static void main(String[] args) { / ...
- 分享知识-快乐自己:SpringMvc中的四种数据源及相关配置(整合快速集成开发)
数据库连接: jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://39.105.105.186:3306/SpringMybatis?us ...
- POJ 2497 Strategies
题意:有三个人,Bill, Steve and Linus,他们参加竞赛,给出竞赛的题目和比赛时间,然后给出每道题需要的时间(他们解同一道题花的时间相同),然后他们有不同的策略来做题.每道题的得分为当 ...
- listen 63
Danger Explainers Convince Kids Better Than Do Edict Issuers An eight-year-old may view a hammer as ...
- kmp算法模板及理解
kmp算法是复杂度为O(n+m)的字符串匹配算法; 首先kmp算法的核心是在模式串中获得next数组,这个数组表示模式串的子串的前缀和后缀相同的最长长度; 这样在匹配的过程中如果指到不匹配的位置,模式 ...
- Qt容器组件(二)之QWidgetStack、QMdiArea、QDockWidget
QT中有九种容器组件,分别是组合框QGroupBox.滚动区QScrollArea.工具箱QToolBox.选项卡QTabWidget.控件栈QWidgetStack.框架QFrame.组件QWidg ...
- 递归/非递归----python深度遍历二叉树(前序遍历,中序遍历,后序遍历)
递归代码:递归实现很简单 '二叉树结点类' class TreeNode: def __init__(self, x): self.val = x self.left = None self.righ ...