一、服务端代码:
class Http_server
{
public $host = '127.0.0.1';
public $port = 9911;
public $http;
public function __construct()
{
$this->http = new swoole_http_server($this->host,$this->port);
$this->http->set([
'enable_static_handler' => true,//开启静态文件分发
'document_root' => '/www/data'//静态文件根目录
]);
$this->http->on('request',[$this,'onRequest']);
$this->http->start();
}
/**
* @FunctionName :onRequest
* @CreateTime :2019 2019/1/1 22:15
* @Author :Robin
* @Descript 监听http请求事件
* @param $request mixed 接收的数据
* @param $response mixed 返回的数据
*/
public function onRequest($request,$response)
{
echo '<pre>';
var_dump($request->get);
$response->end("<h1>httpserver</h1>");
}
}
$obj = new Http_server();
二、静态文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>This is Httpserver!</h1>
</body>
</html>
三、效果图:
服务端:
服务端带参数访问:
此时服务端打印接收到的参数
服务端直接访问静态资源:
对比两次请求返回的html,访问静态资料时,服务端返回的是/www/data/目录下的index.html文件,带参数访问时,服务端返回的是代码中end()方法中指定的字符串。
swoole的指出,swoole的httpserver对Http协议的支持并不完整,建议仅作为应用服务器。并且在前端增加Nginx作为代理。
在上述验证中,我都是访问的本机127.0.0.1,因为在外网测试访问不了(端口已经开放,防火墙也关了),不知道是swoole的httpserver仅支持内网还是阿里云服务器的问题,这点有待后来再验证了。
四、需要注意的问题:
服务端监听的端口一定要开放,否则只能本机访问,还有就是老生常谈的防火墙问题