Swoole学习之网络通讯引擎Web服务(四)

1、HTTP服务

HTTP服务端

咱们看Swoole官方文档入门指引->快速起步->建立Web服务器,把文档的示例代码跑一次,看下效果:php

http_server.phphtml

<?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内容,并结束此请求。swoole

  • 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逻辑,须要咱们这里作特殊的配置cookie

<?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();
相关文章
相关标签/搜索