Created
August 19, 2021 12:54
-
-
Save azole/4953491d7d798553a0121447591c01cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 0.0.0.0 表示監聽所有 IP 地址 | |
$http = new Swoole\Http\Server('0.0.0.0', 9501); | |
$http->set([ | |
// 可以 host static files | |
// 但不建議這樣做,靜態檔案還是讓 nginx 來 | |
'enable_static_handler' => true, | |
// 'http_autoindex' => false, | |
// 配置静态文件根目录,与 enable_static_handler 配合使用。 | |
// 就可以開啟 http://127.0.0.1:9501/test-ws.html | |
'document_root' => realpath(__DIR__.'/'), | |
// 設定 worker number 數量 | |
//'worker_num' => swoole_cpu_num() * 2, | |
// 設為背景 | |
//'daemonize' => 1, | |
// 設定 log file | |
//'log_file' => '/home/ubuntu/swoole/app.log', | |
]); | |
$http->on("Start", function($server) { | |
echo "Swoole https server is starte at http://127.0.0.1:9501\n"; | |
echo $server->master_pid . "\n"; | |
}); | |
$http->on("shutdown", function($server) { | |
echo $server->master_pid . "\n"; | |
echo "Server is shutting down.\n"; | |
}); | |
$title = ""; | |
// 可以用 htop -t 或 pstree -ap 來觀察 worker process 跟 task worker process | |
$http->on('workerStart', function($server, $worker_id) use(&$title) { | |
// hot reload demo | |
require_once "index.php"; | |
$title = $message; | |
echo "Read from file {$title}.\n"; | |
// kill -USR1 pid | |
// SIGTERM用于停止服务器 | |
// SIGUSR1用于重启全部的Worker进程 | |
// SIGUSR2用于重启全部的Task Worker进程 | |
global $argv; | |
if($worker_id >= $server->setting['worker_num']) { | |
swoole_set_process_name("php {$argv[0]} task worker"); | |
} else { | |
swoole_set_process_name("php {$argv[0]} worker"); | |
} | |
}); | |
// 當有新的 HTTP 請求進入時會觸發此事件 | |
// 如果使用 chrome 會額外產生一次 favicon.ico 的 request | |
$http->on('Request', function(Swoole\Http\Request $req, Swoole\Http\Response $res) use(&$title) { | |
// Swoole\Http\Request 會保留 client 相關資訊,GET, POST, COOKIE, Header 等 | |
var_dump($req->get, $req->post); | |
var_dump($req->server['path_info']); | |
if($req->server['path_info'] == '/favicon.ico' || $req->server['request_uri'] == '/favicon.ico') { | |
$res->end(); | |
return; | |
} | |
$res->header('Content-Type', 'text/html;charset=utf-8'); | |
// hot reload demo | |
echo "test echo {$title}\n"; | |
$res->end("<h1>{$title}</h1>"); | |
}); | |
$http->start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment