c++
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <chrono>
#include <thread>
#include <uv.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include "file.pb.h"
using namespace std;
using namespace google::protobuf::io;
namespace chrono = std::chrono;
// 创建目录(包括父目录)
bool CreateDirectoryRecursively(const string& path) {
size_t pos = 0;
string parent;
while ((pos = path.find('/', pos + 1)) != string::npos) {
parent = path.substr(0, pos);
if (!boost::filesystem::exists(parent)) {
if (!boost::filesystem::create_directory(parent)) {
cerr << "Error creating directory " << parent << endl;
return false;
}
}
}
return true;
}
// 从连接请求中读取文件信息对象
unique_ptr<FileMessage> ReadFileMessage(uv_stream_t* stream) {
unique_ptr<CodedInputStream> coded_input(new CodedInputStream(new uv_streambuf(stream)));
uint32_t message_size;
coded_input->ReadVarint32(&message_size);
string message_data;
coded_input->ReadString(&message_data, message_size);
unique_ptr<FileMessage> file_message(new FileMessage());
file_message->ParseFromString(message_data);
return file_message;
}
// 处理连接请求,异步接收文件夹中所有文件
void AllocBuffer(uv_handle_t* handle, std::size_t suggested_size, uv_buf_t* buf) {
buf->base = new char[suggested_size];
buf->len = suggested_size;
}
void HandleConnection(uv_stream_t* stream, const string& dirname) {
// 读取目录名
unique_ptr<FileList> file_list(ReadFileMessage(stream));
if (!file_list) {
cerr << "Failed to read FileList message." << endl;
uv_close((uv_handle_t*)stream, nullptr);
return;
}
const string& received_dirname = file_list->dirname();
// 创建目录
boost::filesystem::path received_path(received_dirname);
boost::filesystem::path save_path(dirname);
boost::filesystem::path new_path = save_path / received_path.filename();
if (!CreateDirectoryRecursively(new_path.string())) {
cerr << "Failed to create directory " << new_path << endl;
uv_close((uv_handle_t*)stream, nullptr);
return;
}
// 遍历目录中所有文件,异步接收文件
uv_buf_t buf;
uv_streambuf_t streambuf;
uv_streambuf_init(uv_default_loop(), &streambuf, 0);
while (true) {
int nread = uv_read2_start(stream, AllocBuffer, [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
if (nread < 0) {
cerr << "Error reading from stream: " << uv_strerror(nread) << endl;
uv_close((uv_handle_t*)stream, nullptr);
delete[] buf->base;
} else if (nread > 0) {
unique_ptr<FileMessage> file_message(ReadFileMessage(stream));
if (!file_message) {
cerr << "Failed to read FileMessage." << endl;
uv_close((uv_handle_t*)stream, nullptr);
delete[] buf->base;
return;
}
const string& filename = file_message->filename();
const string& file_data = file_message->data();
const uint64_t size = file_message->size();
const uint64_t modify_time = file_message->modify_time();
// 拼接文件保存路径
boost::filesystem::path file_path(filename);
boost::filesystem::path save_path(dirname);
boost::filesystem::path new_path = save_path / received_path.filename() / file_path.relative_path();
new_path = boost::filesystem::absolute(new_path);
// 覆盖写入文件
ofstream file(new_path.string(), ios::binary);
if (!file || !file.write(file_data.c_str(), file_data.size())) {
cerr << "Failed to write file: " << filename << endl;
} else {
// 设置文件大小和修改日期
struct utimbuf new_times;
new_times.actime = new_times.modtime = modify_time;
if (utime(new_path.string().c_str(), &new_times) != 0) {
cerr << "Failed to set modify time for file: " << filename << endl;
} else {
cout << "Received file: " << filename << ", size: " << size << ", modify time: " << modify_time << endl;
}
}
uv_streambuf_init(uv_default_loop(), &streambuf, 0);
} else {
delete[] buf->base;
}
});
if (nread < 0) {
if (nread != UV_EOF) {
cerr << "Error reading from stream: " << uv_strerror(nread) << endl;
}
uv_close((uv_handle_t*)stream, nullptr);
break;
} else {
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
}
}
// 异步等待连接请求
void OnConnect(uv_stream_t* server, int status) {
uv_tcp_t* client = new uv_tcp_t;
uv_tcp_init(uv_default_loop(), client);
uv_accept(server, (uv_stream_t*)client);
uv_read_start((uv_stream_t*)client, [](uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
buf->base = new char[suggested_size];
buf->len = suggested_size;
}, [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
if (nread < 0) {
cerr << "Error reading from stream: " << uv_strerror(nread) << endl;
uv_close((uv_handle_t*)stream, nullptr);
delete[] buf->base;
} else {
HandleConnection(stream, ".");
}
});
}
void WaitForConnection(uint16_t port) {
uv_tcp_t* server = new uv_tcp_t;
uv_tcp_init(uv_default_loop(), server);
sockaddr_in addr;
uv_ip4_addr("0.0.0.0", port, &addr);
uv_tcp_bind(server, (const sockaddr*)&addr, UV_TCP_IPV4ONLY);
int r = uv_listen((uv_stream_t*)server, 128, OnConnect);
if (r) {
cerr << "Error listening on port " << port << ": " << uv_strerror(r) << endl;
return;
}
cout << "Waiting for connections on port " << port << "..." << endl;
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
int main(int argc, char* argv[]) {
if (argc < 2) {
cerr << "Usage: " << argv[0] << " port" << endl;
return 1;
}
const uint16_t port = stoi(argv[1]);
uv_loop_t* loop = uv_default_loop();
async(std::launch::async, WaitForConnection, port);
uv_run(loop, UV_RUN_DEFAULT);
return 0;
}