服务端代码
http_server.php
<?php// 参数1 : 监听的IP地址// 参数2 : 监听的端口$server = new Swoole\Http\Server('0.0.0.0', 9505);// HTTP 服务器只需要关注请求响应即可,所以只需要监听一个 onRequest 事件。// 当有新的 HTTP 请求进入就会触发此事件。// $request 对象,包含了请求的相关信息,如 GET/POST 请求的数据。$server->on('request', function($request, $response){// 为了解决 chrome 请求两次的问题if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {$response->end();return;}echo '<pre>';var_dump($request->get, $request->post);// 设置返回的响应头信息$response->header("Content-type", 'text/html;charset=utf-8');// 表示输出一段 HTML 内容,并结束此请求。$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");});$server->start();?>
客户端
客户端访问 : http://192.168.8.128:9505/?id=2 , 其中 192.168.8.128 替换成你本地的 ip 地址, 就可以执行一个 http请求.
执行结果
[root@localhost wwwroot]# php http_server.php<pre>array(1) {["id"]=>string(1) "2"}NULL
Chrome请求两次
使用 Chrome 浏览器访问服务器,会产生额外的一次请求,/favicon.ico,可以在代码中响应 404 错误。
$http->on('request', function ($request, $response) {if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {$response->end();return;}var_dump($request->get, $request->post);$response->header("Content-Type", "text/html; charset=utf-8");$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");});
URL 路由
应用程序可以根据 $request->server['request_uri'] 实现路由。如:http://127.0.0.1:9501/test/index/?a=1,代码中可以这样实现 URL 路由。
$http->on('request', function ($request, $response) {// trim($request->server['request_uri'], '/') = test/indexlist($controller, $action) = explode('/', trim($request->server['request_uri'], '/'));// 根据 $controller, $action 映射到不同的控制器类和方法(new $controller)->$action($request, $response);});
