swoole基础之http-server

    一般我们使用的http服务器都是例如Apache和NGINX的较多,同样swoole本身也自带了http的这种服务,可以直接进行使用,但是在这个的上层我们一般会加nginx服务进行fastcgi转发到swoole的http服务中.

   一般我们在测试的使用可以使用两种常见的方式进行http服务的测试

  1. 使用浏览器直接访问地址 +端口    (要HTTPserver要绑定0.0.0.0都可以进行访问  端口设置要避免冲突)

使用命令行

curl http://127.0.0.1:8800?name=x-wolf

                                                                                                                                                                                                                    

       作为web服务器一般我们都会有这样的需求,当静态资源的时候我们希望他直接去访问静态文件,而对于动态资源再执行平常的请求.实现与nginx/Apache一样的动静态资源的处理方式.

//需要设置HTTPserver参数

$http = new swoole_http_server('0.0.0.0',8811);

$http->set([
        'enable_static_handler' =>      true, //设置静态资源处理
        'document_root'         =>      '/usr/local/nginx/html/swoole/server/data', //设置静态资源放置的地址
]);

  

    2. 当使用nginx作为代理转发的时候,需要进行一些配置

server
{
    listen 2017;
    #server_name 110.255.42.22;

    location /
    {
        root html;
        index index.html index.htm;
    }
    location ~ \.php$
    {
        proxy_http_version 1.1;
        proxy_set_header Connection "keep-alive";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://127.0.0.1:9501; //转发到9501
    }
}

    此时需要开启swoole的http服务

$http = new swoole_http_server("127.0.0.1", 9501);
$http->set(
array(
    'reactor_num'=>2,
    'worker_num'=>16
)
);
$http->on('request', function ($request, $response) {
    $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();

注意点:

  1. 在服务端打印内容不会显示在浏览器中(print var_dump...)   他会将内容打印到终端中
  2. 要想返回到客户端中显示,使用自带方法即可
    $response->write('输出内容');
    
    $response->end('最后内容,此后再无内容输出'); 

猜你喜欢

转载自blog.csdn.net/lixing112233/article/details/85210586