swoole學習之: 運行第一個http服務

接續我們前面設置的centos虛擬機, ip: 10.0.2.7, 把端口81映射到本機的40181

實現一個http服務

我們寫一個http.php文件:

$http = new Swoole\Http\Server('10.0.2.7', 81);//外部訪問: http://127.0.0.1:40181

$http->on('start', function ($server) {
    echo "Swoole http server is started at http://10.0.2.7:81".PHP_EOL;
});

$http->on('request', function ($request, $response) {
    $response->header('Content-Type', 'text/plain');
    $response->end('Hello World, '.date('Y-m-d H:i:s').PHP_EOL);
});

$http->start();

上面啓動了一個http服務, 監聽81端口. 我們可以使用虛擬機10.0.2.7這個ip, 也可以使用0.0.0.0. 如果是橋接網卡, 那麼可以使用任意一個ip地址.

然後執行: php http.php 啓動服務

查看下php程序的執行狀況 ps -ef | grep php:

注意圖中有5個進程, 如果我們需要終止swoole服務, 可以ctrl+c, 或者kill pid(只要kill最上面那個2483即可)

那好, 我們現在來訪問一下 http://127.0.0.1:40181

Nailed it!

數據輸出

我們現在來修改一下代碼, 輸出get參數;

$http->on('request', function ($request, $response) {
    $response->header('Content-Type', 'text/plain');
    $response->write(json_encode($request->get).PHP_EOL);
    $response->write('Hello World, '.date('Y-m-d H:i:s').PHP_EOL);
});

URL 路由

按官方教程內容, 還可以根據 $request->server['request_uri'] 實現路由。如:http://127.0.0.1:9501/test/index/?a=1,代碼中可以這樣實現 URL 路由。

$http->on('Request', function ($request, $response) {
    list($controller, $action) = explode('/', trim($request->server['request_uri'], '/'));
    //根據 $controller, $action 映射到不同的控制器類和方法
    (new $controller)->$action($request, $response);
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章