在 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)