Swoole从入门到入土(12)——HTTP服务器[Response]

继上一节了解完请求对象之后,这一节我们着重了解响应对象(Response)。响应对象主要用于将数据发现到客户端。当 Response 对象销毁时,如果未调用 end 发送 HTTP 响应,底层会自动执行 end("")。

关于Response需要注意的是:千万不要使用 & 符号引用 HttpResponse 对象。

1、函数

header():设置 HTTP 响应的 Header 信息

SwooleHttpResponse->header(string $key, string $value, bool $ucwords = true);

$key:HTTP 头的 Key

$value:HTTP 头的 value

$ucwords:是否需要对 Key 进行 HTTP 约定格式化【默认 true 会自动格式化】

返回值:设置失败,返回 false。设置成功,没有任何返回值。

注意:
- header 设置必须在 end 方法之前 -$key 必须完全符合 HTTP 的约定,每个单词首字母大写,不得包含中文,下划线或者其他特殊字符
- $value 必须填写
- $ucwords 设为 true,底层会自动对 $key 进行约定格式化
- 重复设置相同 $key 的 HTTP 头会覆盖,取最后一次

trailer():将 Header 信息附加到 HTTP 响应的末尾,仅在 HTTP2 中可用,用于消息完整性检查,数字签名等。

SwooleHttpResponse->trailer(string $key, string $value, bool $ucwords = true);

$key:HTTP 头的 Key

$value:HTTP 头的 value

$ucwords:是否需要对 Key 进行 HTTP 约定格式化【默认 true 会自动格式化】

返回值:设置失败,返回 false。设置成功,没有任何返回值。

注意:重复设置相同 $key 的 Http 头会覆盖,取最后一次。

cookier():设置 HTTP 响应的 cookie 信息。此方法参数与 PHP 的 setcookie 完全一致。

SwooleHttpResponse->cookie(string $key, string $value = '', int $expire = 0 , string $path = '/', string $domain  = '', bool $secure = false , bool $httponly = false, string $samesite = '');

注意:

- cookie 设置必须在 end 方法之前
- $samesite 参数从 v4.4.6 版本开始支持
- Swoole 会自动会对 $value 进行 urlencode 编码,可使用 rawCookie() 方法关闭对 $value 的编码处理
- Swoole 允许设置多个相同 $key 的 COOKIE

rawCookie():设置 HTTP 响应的 cookie 信息,参数和上文的 cookie() 一致,只不过不进行编码处理

status():发送 Http 状态码。

SwooleHttpResponse->status(int $http_status_code, int $reason): bool

$http_status_code:设置 HttpCode

$reason:可设置任意 HttpCode

注意:

-如果只传入了第一个参数 $http_status_code 必须为合法的 HttpCode,如 200、502、301、404 等,否则会设置为 200 状态码

-如果设置了第二个参数 $reason,$http_status_code 可以为任意的数值,包括未定义的 HttpCode,如 499

-必须在 $response->end() 之前执行 status 方法

gzip():4.1.0后方法已废弃,故不展开说明

redirect():发送 Http 跳转。调用此方法会自动 end 发送并结束响应。

SwooleHttpResponse->redirect(string $url, int $http_code = 302): void

$url:跳转的新地址,作为 Location 头进行发送

$http_code:状态码【默认为 302 临时跳转,传入 301 表示永久跳转】

write():启用 Http Chunk 分段向浏览器发送相应内容。

SwooleHttpResponse->write(string $data): bool

$data:要发送的数据内容【最大长度不得超过 2M,受 buffer_output_size 配置项控制】

注意:使用 write 分段发送数据后,end 方法将不接受任何参数,调用 end 只是会发送一个长度为 0 的 Chunk 表示数据传输完毕。

sendfile():发送文件到浏览器。

SwooleHttpResponse->sendfile(string $filename, int $offset = 0, int $length = 0): bool

$filename:要发送的文件名称【文件不存在或没有访问权限 sendfile 会失败】

$offset:上传文件的偏移量【可以指定从文件的中间部分开始传输数据。此特性可用于支持断点续传】

$length:发送数据的尺寸【默认文件的尺寸】

注意:

-底层无法推断要发送文件的 MIME 格式因此需要应用代码指定 Content-Type

-调用 sendfile 前不得使用 write 方法发送 Http-Chunk

-调用 sendfile 后底层会自动执行 end

-sendfile 不支持 gzip 压缩

end():发送 Http 响应体,并结束请求处理。

SwooleHttpResponse->end(string $html): bool

$html:要发送的内容

注意:

-end 只能调用一次,如果需要分多次向客户端发送数据,请使用 write 方法

-客户端开启了 KeepAlive,连接将会保持,服务器会等待下一次请求

-客户端未开启 KeepAlive,服务器将会切断连接

detach():分离响应对象。使用此方法后,$response 对象销毁时不会自动 end,与 HttpResponse::create 和 Server::send 配合使用。

SwooleHttpResponse->detach(): bool

注意:detach 方法只能在 SWOOLE_PROCESS 模式下使用。

示例1:某些情况下,需要在 Task 进程中对客户端发出响应。这时可以利用 detach 使 $response 对象独立。在 Task 进程可以重新构建 $response,发起 Http 请求响应。

$http = new SwooleHttpServer("0.0.0.0", 9501);

$http->set(['task_worker_num' => 1, 'worker_num' => 1]);

$http->on('request', function ($req, SwooleHttpResponse $resp) use ($http) {
    $resp->detach();
    $http->task(strval($resp->fd));
});

$http->on('finish', function () {
    echo "task finish";
});

$http->on('task', function ($serv, $task_id, $worker_id, $data) {
    var_dump($data);
    $resp = SwooleHttpResponse::create($data);
    $resp->end("in task");
});

$http->start();

示例 2:某些特殊的场景下,需要对客户端发送特殊的响应内容。HttpResponse 对象自带的 end 方法无法满足需求,可以使用 detach 分离响应对象,然后自行组装 HTTP 协议响应数据,并使用 Server::send 发送数据。

$http = new SwooleHttpServer("0.0.0.0", 9501);

$http->on('request', function ($req, SwooleHttpResponse $resp) use ($http) {
    $resp->detach();
    $http->send($resp->fd, "HTTP/1.1 200 OK
Server: server

Hello World
");
});

$http->start();

create():构造新的 SwooleHttpResponse 对象。

SwooleHttpResponse::create(int $fd): SwooleHttpResponse;

$fd:参数为需要绑定的连接 $fd【调用 HttpResponse 对象的 end 与 write 方法时会向此连接发送数据】

返回值:调用成功返回一个新的 HttpResponse 对象,调用失败返回 false

注意:使用此方法前请务必调用 detach 方法将旧的 $response 对象分离,否则可能会造成对同一个请求发送两次响应内容。

示例:

$http = new SwooleHttpServer("0.0.0.0", 9501);

$http->on('request', function ($req, SwooleHttpResponse $resp) use ($http) {
    $resp->detach();
    $resp2 = SwooleHttpResponse::create($req->fd);
    $resp2->end("hello world");
});

$http->start();

关于Http服务器响应对象的成员函数就以上这些,接下来将会疏理Http服务器的特有配置。

---------------------------  我是可爱的分割线  ----------------------------

最后博主借地宣传一下,漳州编程小组招新了,这是一个面向漳州青少年信息学/软件设计的学习小组,有意向的同学点击链接,联系我吧。

原文地址:https://www.cnblogs.com/ddcoder/p/13795435.html