🛰️航天仿真算法库 SpaceAST 0.3.1
载入中...
搜索中...
未找到
NetworkStreamReceiver.hpp
浏览该文件的文档.
1
21
22#pragma once
23
24#include "AstGlobal.h"
25#include "NetworkResponse.hpp"
26#include "AstUtil/Logger.hpp"
27#include <map>
28#include <string>
29#include <functional>
30#include <cstdint>
31
32AST_NAMESPACE_BEGIN
33
39class NetworkResponse;
40
43class AST_UTIL_API NetworkStreamReceiver
44{
45public:
46 NetworkStreamReceiver() = default;
47 virtual ~NetworkStreamReceiver() = default;
48
53 virtual errc_t onHeaders(int statusCode, const std::map<std::string, std::string>& headers) { return eNoError; }
54
59 virtual errc_t onData(const char* data, size_t size) = 0;
60
63 virtual void onError(errc_t error) {}
64
66 virtual void onComplete() {}
67};
68
69
75{
76public:
78 : response_(response), body_() {}
79
80 errc_t onHeaders(int statusCode, const std::map<std::string, std::string>& headers) override;
81 errc_t onData(const char* data, size_t size) override;
82 void onComplete() override;
83 void onError(errc_t /*error*/) override;
84private:
85 NetworkResponse& response_;
86 std::string body_;
87};
88
91using DownloadProgressCallback = std::function<bool(uint64_t downloaded, uint64_t total)>;
92
93
94
99{
100public:
101 FileDownloadReceiver(const std::string& filepath, const DownloadProgressCallback& progress);
102
103 ~FileDownloadReceiver() override;
104
105 FileDownloadReceiver(const FileDownloadReceiver& other) = delete;
106 FileDownloadReceiver& operator=(const FileDownloadReceiver& other) = delete;
107
108 errc_t onHeaders(int statusCode, const std::map<std::string, std::string>& headers) override;
109 errc_t onData(const char* data, size_t size) override;
110 void onError(errc_t /*error*/) override{}
111
112 uint64_t downloaded() const { return downloaded_; }
113 uint64_t total() const { return total_; }
114
117 errc_t finish();
118
120 void discard();
121
122private:
123 void close();
124
125
126 std::string filepath_;
127 std::string tempPath_;
128 DownloadProgressCallback progress_;
129 FILE* fp_ = nullptr;
130 uint64_t total_ = 0;
131 uint64_t downloaded_ = 0;
132};
133
136AST_NAMESPACE_END
将流式数据收集到 NetworkResponse 的适配器
定义 NetworkStreamReceiver.hpp:75
将流式响应体写入文件并在写盘过程中报告下载进度
定义 NetworkStreamReceiver.hpp:99
void onError(errc_t) override
发生网络错误
定义 NetworkStreamReceiver.hpp:110
定义 NetworkResponse.hpp:37
流式数据接收器
定义 NetworkStreamReceiver.hpp:44
virtual void onComplete()
数据接收完毕(正常完成时触发)
定义 NetworkStreamReceiver.hpp:66
virtual errc_t onData(const char *data, size_t size)=0
收到一块响应体数据(可能被多次调用)
virtual errc_t onHeaders(int statusCode, const std::map< std::string, std::string > &headers)
收到 HTTP 响应头(在 onData 之前触发一次)
定义 NetworkStreamReceiver.hpp:53
virtual void onError(errc_t error)
发生网络错误
定义 NetworkStreamReceiver.hpp:63
std::function< bool(uint64_t downloaded, uint64_t total)> DownloadProgressCallback
定义 NetworkStreamReceiver.hpp:91