Swoole
  1. 入门
    1. Swoole - 入门 - 安装
    2. Swoole - 入门 - 创建TCP服务器
    3. Swoole - 入门 - 创建UDP服务器
    4. Swoole - 入门 - 创建HTTP服务器
    5. Swoole - 入门 - 创建websocket服务器
    6. Swoole - 入门 - 创建同步TCP客户端
    7. Swoole - 入门 - 创建异步TCP客户端
    8. Swoole - 入门 - 网络通信协议设计
    9. Swoole - 入门 - 使用异步客户端(MySQL,Redis,Http)

Swoole - 入门 - 创建HTTP服务器

程序员日记      2019-09-19

创建HTTP服务器

server.php

<?php
$http = new Swoole\Http\Server("0.0.0.0", 9503);
$http->on('request', function ($request, $response) {
//Chrome 会产生额外的一次请求,/favicon.ico,可以在代码中响应404错误。   
if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {
        return $response->end();
    }
    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.

9503 监听的端口,如果被占用程序会抛出致命错误,中断执行。


启动服务

php server.php

访问(演示用的是虚拟机,所以是局域网IP)

http://192.168.0.99:9503
http://192.168.0.99:9503/?id=100&aaa=10