Swoole为何采用命令行启动方式?

2026-05-07 04:371阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计343个文字,预计阅读时间需要2分钟。

Swoole为何采用命令行启动方式?

相关专题

基于 swoole 的服务端应该在命令行方式下运行,以保证只有一个实例(端口是不能重复打开的)

我们用 Swoole 来做一个           (推荐学习: swoole视频教程)

<?php $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/ 下输出, 怎么写呢?

<?php $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

本文共计343个文字,预计阅读时间需要2分钟。

Swoole为何采用命令行启动方式?

相关专题

基于 swoole 的服务端应该在命令行方式下运行,以保证只有一个实例(端口是不能重复打开的)

我们用 Swoole 来做一个           (推荐学习: swoole视频教程)

<?php $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/ 下输出, 怎么写呢?

<?php $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