一、官网的例子创建服务器
$http = new swoole_http_server('0.0.0.0',80);
//设置document_root并设置enable_static_handler为true后,
// 底层收到Http请求会先判断document_root路径下是否存在此文件,如果存在会直接发送文件内容给客户端,不再触发onRequest回调
$http->set([
'enable_static_handler' => true, // 是否开启静态资源访问
'document_root' => '/www/wwwroot/linu.yeyuqian.top/swoole_http/' // 静态资源目录
]);
$http->on('request',function($request, $response){
print_r($request->get);
$response->end("<h1>HTTPserver</h1>".json_encode($request->get));
});
$http->start();
- 在命令窗口执行 php http_server.php
- 然后访问解析的域名 http:// www.abc.com/+静态文件的地址,我的是http:// www.abc.com/index.html就可以访问到index.html的内容
二、面向对象的方式
这是一个引入第三方框架的列子,我把引入的方法注释了,变成一个普通的http服务器文件
class HttpServer{
private $port = 80;
private $host = '0.0.0.0';
private $http = null;
public function __construct(){
$this->http = new swoole_http_server($this->host, $this->port);
$this->http->set([
'enable_static_handler' => true,
'document_root' => '/www/wwwroot/linu.yeyuqian.top/swoole_http/'
]);
$this->http->on("workerstart", [$this, 'onWorkerStart']);
$this->http->on("request", [$this, 'onRequest']);
$this->http->on("close", [$this, 'onClose']);
$this->http->start();
}
/**
* 此事件在Worker进程/Task进程启动时发生,这里创建的对象可以在进程生命周期内使用
* 在onWorkerStart中加载框架的核心文件后
* 1.不用每次请求都加载框架核心文件,提高性能
* 2.可以在后续的回调中继续使用框架的核心文件或者类库
*
* @param $server
* @param $worker_id
*/
public function onWorkerStart($server, $worker_id) {
// 定义应用目录
// define('APP_PATH', __DIR__ . '/../../../../application/');
// // 加载框架里面的文件
// require __DIR__ . '/../../../../thinkphp/base.php';
}
/**
* request回调
* 输入的变量例:$_SERVER = []
* @param $request
* @param $response
*/
public function onRequest($request, $response) {
$_SERVER = [];
if(isset($request->server)) {
foreach($request->server as $k => $v) {
$_SERVER[strtoupper($k)] = $v;
}
}
if(isset($request->header)) {
foreach($request->header as $k => $v) {
$_SERVER[strtoupper($k)] = $v;
}
}
$_GET = [];/ / 接收get请求的参数
if(isset($request->get)) {
foreach($request->get as $k => $v) {
$_GET[$k] = $v;
}
}
$_POST = []; / / 接收post请求的参数
if(isset($request->post)) {
foreach($request->post as $k => $v) {
$_POST[$k] = $v;
}
}
$_POST['http_server'] = $this->http;
// ob_start();
// // 执行应用并响应
// try {
// think\Container::get('app', [APP_PATH])
// ->run()
// ->send();
// }catch (\Exception $e) {
// // todo
// }
// $res = ob_get_contents();
// ob_end_clean();
$res = 121321;
$response->end($res);
}
/**
* close
* @param $http
* @param $fd
*/
public function onClose($http, $fd) {
echo "clientid:{$fd}\n";
}
}
new HttpServer();
网友评论