swoole学习(三):HTTP服务

http_server.php:

$http = new Swoole\Http\Server("0.0.0.0", 9501);

$http->on('request', function ($request, $response) {
    var_dump($request->get, $request->post);
    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});

$http->start();

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 监听的端口,如果被占用程序会抛出致命错误,中断执行。

启动服务:phphttp_server.php

打开浏览器输入http:127.0.0.1:9501查看测试

猜你喜欢

转载自www.cnblogs.com/jongty/p/12716798.html
今日推荐