咱们看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
当为静态页面如 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();