swoole: PHP的协程高性能网络通信引擎,运用完整同步的代码完成异步顺序。PHP代码无需分外增添任何关键词,底层自动举行协程调理,完成异步IO。
基于 swoole 的服务端应该在命令行体式格局下运转,以保证只要一个实例(端口是不能反复翻开的)
我们用 Swoole 来做一个 (引荐进修: swoole视频教程)
$http = new swoole_http_server('0.0.0.0', 80, SWOOLE_BASE);
$http->on('request', function(swoole_http_request $req, swoole_http_response $res) use($http) {
$res->write("hello world");
$res->end();
});
OK, 看出了吧, 不依赖框架/ ob_flush 等机制, Swoole 不能再运用 echo 作为输出要领了, 得运用$res->write(String $content) 和 $res->end(String $endContent).
那末我们怎样接见它呢?
命令行启动
php app.php
# 你在代码内里 echo/var_dump/print(_r) 的内容将在这里输出
然后在浏览器翻开 http://localhost/ 就能够获得 hello world 的输出.
但是发明了吗? http://localhost/ 和 http://localhost/xxx 都输出一样的内容.
假如我们只想让 php 在 http://localhost/ 下输出, 怎样写呢?
$http = new swoole_http_server('0.0.0.0', 80, SWOOLE_BASE);
$http->on('request', function(swoole_http_request $req, swoole_http_response $res) use($http) {
if($req->server['request_uri'] == '/'){
$res->write("hello world");
$res->end();
return;
}
$res->end('404');
return;
});
\Swoole_http_request $req 包含了许多我们未来能用到的要求数据. 包含 $req->server, $req->get, $req->post, 数组构造, ->server的KEY 为小写
以上就是swoole为何要用命令行来启动的细致内容,更多请关注ki4网别的相干文章!
收藏 | 0