-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_send_file_test.cpp
79 lines (58 loc) · 2.04 KB
/
server_send_file_test.cpp
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
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include <boost/asio.hpp>
#include <openssl/md5.h>
#include <iostream>
#include <fstream>
#include <boost/asio.hpp>
#include <openssl/md5.h>
using boost::asio::ip::tcp;
std::string get_file_md5(const std::string& file_name) {
unsigned char result[MD5_DIGEST_LENGTH];
std::ifstream file(file_name, std::ios::binary);
std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
MD5((unsigned char*)&buffer[0], buffer.size(), result);
std::ostringstream sout;
sout<<std::hex<<std::setfill('0');
for(long long c: result) {
sout<<std::setw(2)<<(long long)c;
}
return sout.str();
}
void send_file(tcp::socket& socket, const std::string& file_name) {
std::ifstream file(file_name, std::ios::binary);
if (!file.is_open() || file.fail()) {
std::cerr << "Failed to open the file.\n";
return;
}
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> file_data(size);
if (!file.read(file_data.data(), size)) {
std::cerr << "Failed to read the file.\n";
return;
}
std::string md5 = get_file_md5(file_name);
std::cout << "MD5 of the file to be sent: " << md5 << std::endl;
std::cout << "Size of the file to be sent: " << size << " bytes\n";
boost::asio::write(socket, boost::asio::buffer(md5));
std::size_t written = boost::asio::write(socket, boost::asio::buffer(file_data));
std::cout << "Written bytes: " << written << "\n";
}
int main() {
try {
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 1234));
for (;;) {
tcp::socket socket(io_service);
acceptor.accept(socket);
send_file(socket, "file_to_send.bin");
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}