Swoole入門到實戰(一)PHP7&Swoole源碼安裝、玩轉網絡通信引擎、異步非堵塞IO場景

2.3HTTP服務(常用)

ALT

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

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

$http->start();

開啓http服務:(監聽到了請求)

測試:
1)直接curl請求

2)瀏覽器訪問

http返回的cookies: singwa

設置document_root並設置enable_static_handler爲true後,底層收到Http請求會先判斷document_root路徑下是否存在此文件,如果存在會直接發送文件內容給客戶端不再觸發onRequest回調

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

$http->set([
    'document_root' => '/usr/local/apache/htdocs/swoole/data',
    'enable_static_handler' => true,
]);

$http->on('request', function ($request, $response) {
    var_dump($request->get); // 瀏覽器打開會多出一個null?
    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->cookie("singwa",'xsssss', time() + 1800);
    $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>".json_encode($request->get));
});

$http->start();

文件結構
index.html內容
s/index.html內容

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章