HTTP 協議是建立在 TCP/IP協議 基礎上的協議 ,也就是說,在通過 TCP 三次握手建立了連接之後,數據之間的傳輸需要遵循約定好的規範,如請求報文、響應報文等。
現今主流開源的 HTTP 服務器分別是 apache、 nginx 。除此之外,Swoole 也可以快速搭建 HTTP 服務器。
1. 創建腳本:http_server.php
<?php
// 創建 Server 對象,0.0.0.0 監聽全部地址:9501端口
$http = new Swoole\Http\Server("0.0.0.0", 9501);
// 配置
$http->set([
// 開啓靜態文件請求處理功能
"enable_static_handler" => true,
// 默認訪問的靜態目錄
"document_root" => "/usr/share/nginx/html"
]);
/**
* 監聽請求
* @param $request 獲取客戶端http請求信息(header/get/post/cookie)
* @param $response 設置服務端http響應對象(cookie/header/status)
*/
$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</h1>");
});
// 啓動服務
$http->start();
2. 執行腳本:
php73 http_server.php
3. 瀏覽器訪問:
4. 結果返回