Swoole入门 - Web 服务
2019-06-01 本文已影响0人
铁匠简记
HTTP服务应用广泛,是我们必须掌握的。
常规的HTTP服务器的处理流程:
用户发起请求nginx,nginx通过fpm发到php,php做最终的逻辑代码执行,然后返回给前端用户。
fpm是FastCGI的进程管理器,fpm会通过用户配置管理一批的FastCGI进程。
使用swoole的httpserver,就不再需要使用fmp,http直接请求swoole的httpserver,直接执行PHP代码逻辑。
Http服务器只需要关注请求响应即可,所以只需要监听一个onRequest事件。当有新的Http请求进入就会触发此事件。事件回调函数有2个参数,一个是$request对象,包含了请求的相关信息,如GET/POST请求的数据。
创建HTTP服务
<?php
$http = new Swoole\Http\Server("0.0.0.0", 8811);
$http->on('request', function ($request, $response) {
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
nginx+swoole配置
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
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:8811;
}

另外一个是response对象,对request的响应可以通过操作response对象来完成。$response->end()方法表示输出一段HTML内容,并结束此请求。
0.0.0.0 表示监听所有IP地址,一台服务器可能同时有多个IP,如127.0.0.1本地回环IP、192.168.1.100局域网IP、210.127.20.2 外网IP,这里也可以单独指定监听一个IP。
8811 监听的端口,如果被占用程序会抛出致命错误,中断执行。
设置文件根目录
document_root:需要返回真正的html内容而不是swoole中response->end()中的内容;但是必须和 enable_static_handler 同时使用。
<?php
$http = new Swoole\Http\Server("0.0.0.0", 8811);
$http->set(
[
'enable_static_handler' => true,
'document_root' => '/opt/work/htdocs/swoole_mooc/demo/data'
]
);
$http->on('request', function ($request, $response) {
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();


接收参数
<?php
$http = new Swoole\Http\Server("0.0.0.0", 8811);
$http->set(
[
'enable_static_handler' => true,
'document_root' => '/opt/work/htdocs/swoole_mooc/demo/data'
]
);
$http->on('request', function ($request, $response) {
$response->end('params:'.json_encode($request->get));
});
$http->start();

#### 接收指定参数
<?php
$http = new Swoole\Http\Server("0.0.0.0", 8811);
$http->set(
[
'enable_static_handler' => true,
'document_root' => '/opt/work/htdocs/swoole_mooc/demo/data'
]
);
$http->on('request', function ($request, $response) {
$response->end('params:'.json_encode($request->get['name']));
});
$http->start();

设置cookie
<?php
$http = new Swoole\Http\Server("0.0.0.0", 8811);
$http->on('request', function ($request, $response) {
$cookieValue = $request->get;
$response->cookie('user', json_encode($cookieValue), time() + 1800);
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
