在 4.6 版本中,对 Swoole\Http\Response
进行了一些增强:
- 添加
Http\Response::isWritable
(db56827) (@matyhtf) - 增强
Response\create()
方法,可以独立于 Server 使用 (#3998) (@matyhtf)
再来看一下上一篇文章的示例代码:
use Swoole\Server;
use Swoole\Http\Request;
$server = new Server('127.0.0.1', 9501);
$server->on('Receive', function (Server $server, $fd, $reactor_id, $data) {
/** @var Request $request */
$request = Request::create();
$request->parse($data);
$body = 'Hello, Swoole';
$body_len = strlen($body);
$send_data = "HTTP/1.1 200 OK\r\nServer: swoole-server\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: {$body_len}\r\nConnection: keep-alive\r\n\r\n{$body}";
$server->send($fd, $send_data);
});
$server->start();
需要用户自行处理$send_data
的数据,而此次增强以后,可以这样使用:
use Swoole\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
$server = new Server('127.0.0.1', 9501);
$server->on('Receive', function (Server $server, $fd, $reactor_id, $data) {
/** @var Request $request */
$request = Request::create();
$request->parse($data);
/** @var Response $response */
$response = Response::create($server, $fd);
$response->status(200);
$response->end('Hello, Swoole');
});
$server->start();
还可以这样:
$server->on('Receive', function (Server $server, $fd, $reactor_id, $data) {
/** @var Request $request */
$request = Request::create();
$request->parse($data);
/** @var Response $response */
$response = Response::create([$server, $request], $fd);
$response->status(200);
$response->end('Hello, Swoole');
});
不但异步 Server 中可以使用,而且协程 Server 中也可以使用:
use Swoole\Coroutine\Server;
use Swoole\Coroutine\Server\Connection;
use Swoole\Http\Request;
use Swoole\Http\Response;
use function Swoole\Coroutine\run;
run(function () {
$server = new Server('0.0.0.0', 9501, false);
$server->handle(function (Connection $conn) use ($server) {
$request = Request::create();
while(true) {
$data = $conn->recv();
if (strlen($data) != $request->parse($data) || $request->isCompleted()) {
break;
}
}
$response = Response::create([$conn->exportSocket(), $request]);
$response->end('Hello, Swoole');
});
$server->start();
});
这样就可以直接使用 Http\Response
的 API 进行响应处理,而不用自行组装 HTTP 协议响应数据。
isWritable
isWritable()
用来判断 Http\Response
对象是否已结束 (end
) 或已分离 (detach
),例如:
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
$http = new Server('0.0.0.0', 9501);
$http->on('request', function (Request $req, Response $resp) {
assert($resp->isWritable(), true);
$resp->end('hello');
assert($resp->isWritable(), false);
$resp->setStatusCode(403);
});
$http->start();
如果在调用end()
之后,再次调用相关 API,就会发生错误
PHP Warning: Swoole\Http\Response::setStatusCode(): http response is unavailable (maybe it has been ended or detached)