-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
99 lines (73 loc) · 2.5 KB
/
main.cpp
File metadata and controls
99 lines (73 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <fstream>
#include <thread>
#include "httplib.h"
void server_save_file_handler(
const httplib::Request &req,
httplib::Response &res,
const httplib::ContentReader &content_reader)
{
assert(!req.is_multipart_form_data() && "Multipart is not supported!");
std::fstream file;
file.open("out.dat", std::ios::binary | std::ios::out | std::ios::trunc);
assert(file.is_open() && "Output file failed to open!");
content_reader([&](const char *data, size_t data_length) {
std::cout << "[SERVER] "
<< "Received " << data_length << " bytes" << std::endl;
file.write(data, data_length);
return true;
});
file.close();
std::cout << "[SERVER] "
<< "Receiving done" << std::endl;
res.set_content("Great!", "text/plain");
}
void server_proc()
{
std::cout << "Server started" << std::endl;
httplib::Server http_server;
http_server.set_payload_max_length(1024 * 1024 * 512); // 512 MB
http_server.Post("/", server_save_file_handler);
http_server.listen("localhost", 3000);
}
void client_proc()
{
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Let the server start first
std::cout << "Client started" << std::endl;
httplib::Client http_client("http://localhost:3000");
// Send file
std::fstream file;
file.open("in.dat", std::ios::binary | std::ios::in | std::ios::ate);
assert(file.is_open() && "Input file failed to open!");
size_t file_size = file.tellg();
file.seekg(0);
httplib::Result response = http_client.Post(
"/", [&](size_t offset, httplib::DataSink &sink) {
char data[8192] = {0};
file.seekg(offset);
file.read(data, sizeof(data));
assert(!file.bad() && "File is bad!");
size_t data_length = file.gcount();
std::cout << "[CLIENT] "
<< "Sending " << data_length << " bytes" << std::endl;
sink.write(data, data_length);
if (file.eof())
{
std::cout << "[CLIENT] "
<< "Sending done" << std::endl;
sink.done();
}
return true;
},
"application/octet-stream");
file.close();
std::cout << "[CLIENT] "
<< "Response: " << response.value().body << std::endl;
}
int main()
{
std::thread server(server_proc);
std::thread client(client_proc);
server.join();
client.join();
}