您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
workerman的http服务-响应-重定向 - 发送文件(实现文件下载服务)
发布时间:2021-12-06 23:35:26编辑:雪饮阅读()
同样的,发送文件需要使用Workerman\Protocols\Http\Response响应类。
发送文件时用以下方式
$response = (new Response())->withFile($file);
$connection->send($response);
workerman支持发送超大文件。workerman会根据客户端接收速度来优化文件读取发送速度,保证最快速发送文件的同时将内存占用减少到最低。
发送文件时会自动加上Last-Modified头,以便下次请求时服务端判断是否发送304响应以节省文件传输提高性能。
发送的文件会自动使用合适的Content-Type头发送给浏览器。
如果文件不存在,会自动转为404响应
实例:
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('http://0.0.0.0:8484');
$worker->onMessage = function(TcpConnection $connection, Request $request)
{
$file = '/www/wwwroot/www.gaojiupan.cn/www.gaojiupan.cn.tar.gz';
// 检查if-modified-since头判断文件是否修改过
$if_modified_since = $request->header('if-modified-since');
if (!empty($if_modified_since)) {
//filemtime() 函数返回文件内容上次的修改时间。
//date_default_timezone_get — 取得一个脚本中所有日期时间函数所使用的默认时区
$modified_time = date('D, d M Y H:i:s', filemtime($file)) . ' ' . \date_default_timezone_get();
// 文件未修改则返回304
if ($modified_time === $if_modified_since) {
$connection->send(new Response(304));
return;
}
}
// 文件修改过或者没有if-modified-since头则发送文件
$response = (new Response())->withFile($file);
$connection->send($response);
};
// 运行worker
Worker::runAll();
?>
实例运行:
[root@izj6c2jeancylo0ppo4vz5z workerman]# php test.php start
Workerman[test.php] start in DEBUG mode
----------------------------------------- WORKERMAN -----------------------------------------
Workerman version:4.0.22 PHP version:7.0.33
------------------------------------------ WORKERS ------------------------------------------
proto user worker listen processes status
tcp root none http://0.0.0.0:8484 1 [OK]
---------------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.
客户端访问即能进行文件下载:
[root@izj6c2jeancylo0ppo4vz5z ~]# wget http://127.0.0.1:8484
--2021-12-06 17:42:40-- http://127.0.0.1:8484/
Connecting to 127.0.0.1:8484... connected.
HTTP request sent, awaiting response... 200 OK
Length: 477836942 (456M) [application/octet-stream]
Saving to: ‘index.html.2’
100%[======================================================================================================================================================================>] 477,836,942 63.2MB/s in 6.1s
2021-12-06 17:42:46 (74.3 MB/s) - ‘index.html.2’ saved [477836942/477836942]
关键字词:workerman,http,重定向,发送,文件,文件下载
相关文章
- workerman的http服务-响应-重定向 - 发送cookie
- workerman的http服务-响应-快捷响应
- workerman的http服务-响应-更改状态码
- workerman的http服务-响应-更改状态码 - Response类初
- workerman的http服务-响应-发送header
- workerman的http服务-响应-发送header - Response类初
- workerman的http服务-请求-获取请求sessionId
- workerman的http服务-请求-获取请求HTTP版本
- windows通过端口转发实现连接阿里云、腾讯云等远端服
- workerman的http服务-请求-获取请求queryString