一、HTTP 服务
HTTP 服务端
我们看 Swoole 官方文档入门指引 -> 快速起步 -> 创建 Web 服务器,把文档的示例代码跑一次,看下效果:
http_server.php
<?php
$http = new Swoole\Http\Server("0.0.0.0", 9501);
$http->on('request', function ($request, $response) {var_dump($request->get, $request->post);
// cookie 测试
// $response->cookie('name', 'lily', time()+3600);
$response->header("Content-Type", "text/html; charset=utf-8");
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
打开一个窗口,访问该服务:
root@5ee6bfcc1310:~# curl http://127.0.0.1:9501
<h1>Hello Swoole. #9147</h1>root@5ee6bfcc1310:~# curl http://127.0.0.1:9501?act=all
<h1>Hello Swoole. #4674</h1>root@5ee6bfcc1310:~#
Http 服务器只需要关注请求响应即可,所以只需要监听一个 onRequest 事件。当有新的 Http 请求进入就会触发此事件。事件回调函数有 2 个参数,一个是 $request 对象,包含了请求的相关信息,如 GET/POST 请求的数据。
另外一个是 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
- 9501 监听的端口,如果被占用程序会抛出致命错误,中断执行。
静态内容
当为静态页面如 test.html 时,不走 php 逻辑,需要我们这里做特殊的配置
<?php
$http = new Swoole\Http\Server("0.0.0.0", 9501);
// 静态资源设置,如果找到相关资源则直接返回给浏览器,不会再走下面的逻辑(仿 Nginx)$http->set([
'enable_static_handle' => true,
'document_root' => "/work/study/code/swoole/static" // 存放静态资源路径
]);
$http->on('request', function ($request, $response) {var_dump($request->get, $request->post);
// cookie 测试
// $response->cookie('name', 'lily', time()+3600);
$response->header("Content-Type", "text/html; charset=utf-8");
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();