// 监听启动事件
$http-on('start', function ($server) {
echo Swoole HTTP server started at http://127.0.0.1:9501\n;
echo Worker number: 、$server-setting['worker_num'] 、\n;
});
// 监听关闭事件
$http-on('shutdown', function ($server) {
echo Swoole HTTP server shutdown.\n;
});
// 启动服务器
$http-start();
▶️ 运行服务器
在终端中执行:
bash
php server.php
你会看到输出:
Swoole HTTP server started at http://127.0.0.1:9501
Worker number: 4
if ($uri === '/') {
$path = __DIR__ 、'/public/index.html';
}
if (is_file($path)) {
$response-header('Content-Type', mime_content_type($path));
$response-end(file_get_contents($path));
return;
}
// 静态资源不存在,返回动态内容
$response-header('Content-Type', 'text/html; charset=utf-8');
$response-end('<h1404 Not Found</h1<pStatic file not found.</p');
});
创建 `public/index.html` 文件测试:
html
<!DOCTYPE html
<html
<head<titleSwoole Static</title</head
<body
<h1Welcome to Swoole Static Server!</h1
<pThis is a static HTML file.</p
</body
</html