change:1.更新子模块,尝试解决子模块的bug及优化。2.client客户端取消日志记录。

This commit is contained in:
taynpg 2025-01-21 14:39:38 +08:00
parent a336e3808b
commit 44735dc387
13 changed files with 141 additions and 112 deletions

View File

@ -143,7 +143,9 @@
"semaphore": "cpp", "semaphore": "cpp",
"span": "cpp", "span": "cpp",
"text_encoding": "cpp", "text_encoding": "cpp",
"*.in": "cpp" "*.in": "cpp",
"hash_map": "cpp",
"stdfloat": "cpp"
}, },
"makefile.configureOnOpen": false, "makefile.configureOnOpen": false,
"C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools" "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools"

View File

@ -28,6 +28,7 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY
${PROJECT_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE}/ ${PROJECT_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE}/
) )
add_definitions(-DFMT_HEADER_ONLY)
include_directories(3rd) include_directories(3rd)
include_directories(.) include_directories(.)
include_directories(${PROJECT_BINARY_DIR}) include_directories(${PROJECT_BINARY_DIR})

View File

@ -13,9 +13,9 @@ namespace fs = boost::filesystem;
namespace fs = std::filesystem; namespace fs = std::filesystem;
#endif #endif
CClient::CClient(const std::shared_ptr<spdlog::logger>& logger) : logger_(logger) CClient::CClient()
{ {
client_ = std::make_shared<CTcpClient>(io_context_, logger_); client_ = std::make_shared<CTcpClient>(io_context_);
supported_.push_back("Get"); supported_.push_back("Get");
sleep_.set_timeout(5000); sleep_.set_timeout(5000);
} }
@ -52,7 +52,7 @@ void CClient::run(const std::string& ip, const std::string& port)
{ {
th_run_ = true; th_run_ = true;
if (!client_->connect(ip, port)) { if (!client_->connect(ip, port)) {
logger_->info("{} connect err.", __FUNCTION__); pinfo("{} connect err.", __FUNCTION__);
return; return;
} }
client_->register_func([&](CFrameBuffer* buf) { handle_frame(buf); }); client_->register_func([&](CFrameBuffer* buf) { handle_frame(buf); });
@ -65,7 +65,7 @@ void CClient::run(const std::string& ip, const std::string& port)
send_frame(bf); send_frame(bf);
delete bf; delete bf;
logger_->warn("SupportCmd:Get|Up|Down|Cancel|Update"); pwarn("SupportCmd:Get|Up|Down|Cancel|Update");
fc_append('|'); fc_append('|');
while (1) { while (1) {
@ -74,7 +74,7 @@ void CClient::run(const std::string& ip, const std::string& port)
break; break;
} }
if (!th_run_ || !client_->is_normal()) { if (!th_run_ || !client_->is_normal()) {
logger_->warn("The link has been closed and cannot be continued. It will automatically exit."); pwarn("The link has been closed and cannot be continued. It will automatically exit.");
break; break;
} }
std::string cmd_input(readline); std::string cmd_input(readline);
@ -96,7 +96,7 @@ void CClient::run(const std::string& ip, const std::string& port)
} }
auto vec = COfStr::split(cmd_input, " "); auto vec = COfStr::split(cmd_input, " ");
if (vec.size() < 2) { if (vec.size() < 2) {
logger_->error("No matched cmd, May be param size incorrect."); perror("No matched cmd, May be param size incorrect.");
continue; continue;
} }
std::string param(cmd_input); std::string param(cmd_input);
@ -115,11 +115,11 @@ void CClient::run(const std::string& ip, const std::string& port)
up_task(param); up_task(param);
continue; continue;
} }
logger_->error("No matched cmd, May be param size incorrect."); perror("No matched cmd, May be param size incorrect.");
} }
client_->disconnect(); client_->disconnect();
thread.join(); thread.join();
logger_->info("{} exit.", __FUNCTION__); pinfo("{} exit.", __FUNCTION__);
} }
bool CClient::get_task_list() bool CClient::get_task_list()
@ -132,17 +132,17 @@ bool CClient::get_task_list()
bool CClient::down_task(const std::string& param) bool CClient::down_task(const std::string& param)
{ {
if (downloading_) { if (downloading_) {
logger_->warn("Have Task Downloading, Please wait....."); pwarn("Have Task Downloading, Please wait.....");
return false; return false;
} }
int id = std::stoi(param); int id = std::stoi(param);
if (!task_list_.count(id)) { if (!task_list_.count(id)) {
logger_->error("No matched id[{}] in task list.", id); perror("No matched id[{}] in task list.", id);
return false; return false;
} }
if (task_list_[id]->id == own_id_) { if (task_list_[id]->id == own_id_) {
logger_->warn("You can't down your own file!!!"); pwarn("You can't down your own file!!!");
return false; return false;
} }
@ -150,7 +150,7 @@ bool CClient::down_task(const std::string& param)
down_ = std::make_shared<TransInfomation>(); down_ = std::make_shared<TransInfomation>();
if (vec.empty()) { if (vec.empty()) {
logger_->warn("No files List, Please Check!"); pwarn("No files List, Please Check!");
return false; return false;
} }
@ -171,7 +171,7 @@ bool CClient::up_task(const std::string& param)
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
for (const auto& item : up_) { for (const auto& item : up_) {
if (item.second->trans_state_ == TRANS_REDAY || item.second->trans_state_ == TRANS_ING) { if (item.second->trans_state_ == TRANS_REDAY || item.second->trans_state_ == TRANS_ING) {
logger_->warn("Have Task Upping, Please wait!"); pwarn("Have Task Upping, Please wait!");
return false; return false;
} }
} }
@ -182,12 +182,12 @@ bool CClient::up_task(const std::string& param)
for (const auto& item : list) { for (const auto& item : list) {
if (!fs::exists(item)) { if (!fs::exists(item)) {
logger_->error("File {} not exist, please check.", item); perror("File {} not exist, please check.", item);
return false; return false;
} }
if (!fs::is_regular_file(item)) { if (!fs::is_regular_file(item)) {
logger_->error("Only Support Up File, But directory.", item); perror("Only Support Up File, But directory.", item);
return false; return false;
} }
@ -198,7 +198,7 @@ bool CClient::up_task(const std::string& param)
} }
} }
if (msg.empty()) { if (msg.empty()) {
logger_->warn("{} msg empty.", __FUNCTION__); pwarn("{} msg empty.", __FUNCTION__);
return false; return false;
} }
@ -220,7 +220,7 @@ bool CClient::cancel_task()
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
for (const auto& item : up_) { for (const auto& item : up_) {
if (item.second->trans_state_ == TRANS_REDAY || item.second->trans_state_ == TRANS_ING) { if (item.second->trans_state_ == TRANS_REDAY || item.second->trans_state_ == TRANS_ING) {
logger_->warn("Have Task Upping, Please wait!"); pwarn("Have Task Upping, Please wait!");
return false; return false;
} }
} }
@ -247,10 +247,10 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons
down_->cur_file_ = fs::path(local_dir).append(remote_file.filename().string()).string(); down_->cur_file_ = fs::path(local_dir).append(remote_file.filename().string()).string();
} }
logger_->warn("Start Down => {} To {}", down_->cur_remote_file_, down_->cur_file_); pwarn("Start Down => {} To {}", down_->cur_remote_file_, down_->cur_file_);
down_->file_.open(down_->cur_file_, std::ios::out | std::ios::binary); down_->file_.open(down_->cur_file_, std::ios::out | std::ios::binary);
if (!down_->file_.is_open()) { if (!down_->file_.is_open()) {
logger_->error("Open {} Failed.", down_->cur_file_); perror("Open {} Failed.", down_->cur_file_);
return false; return false;
} }
@ -261,7 +261,7 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons
buf->data_ = new char[file.size() + 1]; buf->data_ = new char[file.size() + 1];
buf->len_ = std::snprintf(buf->data_, file.size() + 1, "%s", file.data()); buf->len_ = std::snprintf(buf->data_, file.size() + 1, "%s", file.data());
if (!send_frame(buf.get())) { if (!send_frame(buf.get())) {
logger_->error("{} request open file [{}] send failed.", __FUNCTION__, down_->cur_remote_file_); perror("{} request open file [{}] send failed.", __FUNCTION__, down_->cur_remote_file_);
down_->cur_remote_id_.clear(); down_->cur_remote_id_.clear();
down_->cur_remote_file_.clear(); down_->cur_remote_file_.clear();
return false; return false;
@ -277,7 +277,7 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons
CTransProtocal::display_progress(percent); CTransProtocal::display_progress(percent);
} }
if (!th_run_) { if (!th_run_) {
logger_->error("Interrup When Receive File."); perror("Interrup When Receive File.");
report_trans_ret(TRANS_FAILED); report_trans_ret(TRANS_FAILED);
return false; return false;
} }
@ -287,12 +287,10 @@ bool CClient::down_one_file(const std::string& id, const std::string& file, cons
CTransProtocal::display_progress(percent); CTransProtocal::display_progress(percent);
} }
if (cur_file_size_ == cur_down_size_) { if (cur_file_size_ == cur_down_size_) {
logger_->warn("Trans done, close file {}, total:[{}/{}]", down_->cur_file_, cur_down_size_, pwarn("Trans done, close file {}, total:[{}/{}]", down_->cur_file_, cur_down_size_, cur_file_size_);
cur_file_size_);
return true; return true;
} else { } else {
logger_->warn("Trans failed, close file {}, total:[{}/{}]", down_->cur_file_, cur_down_size_, pwarn("Trans failed, close file {}, total:[{}/{}]", down_->cur_file_, cur_down_size_, cur_file_size_);
cur_file_size_);
return false; return false;
} }
} }
@ -337,31 +335,31 @@ bool CClient::request_update_list(const std::string& param)
{ {
auto tvec = COfStr::split(param, " "); auto tvec = COfStr::split(param, " ");
if (tvec.size() < 2) { if (tvec.size() < 2) {
logger_->error("{} invalid param format [{}]", __FUNCTION__, param); perror("{} invalid param format [{}]", __FUNCTION__, param);
return false; return false;
} }
int index = std::stoi(tvec[0]); int index = std::stoi(tvec[0]);
std::string list_file = tvec[1]; std::string list_file = tvec[1];
if (downloading_) { if (downloading_) {
logger_->warn("Have Task Downloading, Please wait....."); pwarn("Have Task Downloading, Please wait.....");
return false; return false;
} }
if (!task_list_.count(index)) { if (!task_list_.count(index)) {
logger_->error("No Index Found {}.", index); perror("No Index Found {}.", index);
return false; return false;
} }
const auto& sr = task_list_[index]; const auto& sr = task_list_[index];
if (sr->id == own_id_) { if (sr->id == own_id_) {
logger_->warn("You can't update your own file!!!"); pwarn("You can't update your own file!!!");
return false; return false;
} }
// 读取list文件 // 读取list文件
std::ifstream in(COfPath::to_full(list_file)); std::ifstream in(COfPath::to_full(list_file));
if (!in.is_open()) { if (!in.is_open()) {
logger_->error("Can't Open File:{}", COfPath::to_full(list_file)); perror("Can't Open File:{}", COfPath::to_full(list_file));
return false; return false;
} }
std::istreambuf_iterator<char> iterf(in); std::istreambuf_iterator<char> iterf(in);
@ -378,11 +376,11 @@ bool CClient::request_update_list(const std::string& param)
if (hitem.empty()) { if (hitem.empty()) {
continue; continue;
} }
logger_->info("---> check {}", hitem); pinfo("---> check {}", hitem);
auto v = COfStr::split(hitem, "|"); auto v = COfStr::split(hitem, "|");
if (v.size() >= 2) { if (v.size() >= 2) {
if (!fs::exists(v[0])) { if (!fs::exists(v[0])) {
logger_->error("file {} not exist.", v[0]); perror("file {} not exist.", v[0]);
valid = false; valid = false;
break; break;
} }
@ -394,7 +392,7 @@ bool CClient::request_update_list(const std::string& param)
} }
if (!valid) { if (!valid) {
logger_->error("Judge List File {} Format Not Passed.", list_file); perror("Judge List File {} Format Not Passed.", list_file);
return false; return false;
} }
@ -406,7 +404,7 @@ bool CClient::request_update_list(const std::string& param)
buf->tid_ = task_list_[index]->id; buf->tid_ = task_list_[index]->id;
if (!send_frame(buf.get())) { if (!send_frame(buf.get())) {
logger_->error("Send Failed {}", __LINE__); perror("Send Failed {}", __LINE__);
return false; return false;
} }
return true; return true;
@ -422,13 +420,13 @@ bool CClient::check_update_list(const std::string& content, std::map<std::string
} }
auto vi = COfStr::split(item, "|"); auto vi = COfStr::split(item, "|");
if (vi.size() != 2) { if (vi.size() != 2) {
logger_->error("Size not 2 {}", item); perror("Size not 2 {}", item);
valid = true; valid = true;
break; break;
} }
if (!fs::exists(vi[1])) { if (!fs::exists(vi[1])) {
valid = false; valid = false;
logger_->error("Not exist {}", vi[1]); perror("Not exist {}", vi[1]);
break; break;
} }
files[vi[0]] = vi[1]; files[vi[0]] = vi[1];
@ -450,10 +448,10 @@ bool CClient::down_update_file(std::map<std::string, std::string> files)
} }
if (suc) { if (suc) {
buf->type_ = TYPE_DONE_UPDATE_LIST; buf->type_ = TYPE_DONE_UPDATE_LIST;
logger_->info("Do Task From {} Done!", buf->tid_); pinfo("Do Task From {} Done!", buf->tid_);
} else { } else {
buf->type_ = TYPE_FAILED_UPDATE_LIST; buf->type_ = TYPE_FAILED_UPDATE_LIST;
logger_->info("Do Task From {} Failed!", buf->tid_); pinfo("Do Task From {} Failed!", buf->tid_);
} }
send_frame(buf.get()); send_frame(buf.get());
return suc; return suc;
@ -464,7 +462,7 @@ bool CClient::send_frame(CFrameBuffer* buf)
char* out_buf{}; char* out_buf{};
int out_len{}; int out_len{};
if (!CTransProtocal::pack(buf, &out_buf, out_len)) { if (!CTransProtocal::pack(buf, &out_buf, out_len)) {
logger_->error("{} pack failed.", __FUNCTION__); perror("{} pack failed.", __FUNCTION__);
return false; return false;
} }
std::lock_guard<std::mutex> lock(send_mut_); std::lock_guard<std::mutex> lock(send_mut_);
@ -479,12 +477,12 @@ bool CClient::send_frame(CFrameBuffer* buf)
void CClient::handle_frame(CFrameBuffer* buf) void CClient::handle_frame(CFrameBuffer* buf)
{ {
if (buf == nullptr) { if (buf == nullptr) {
logger_->error("{} nullptr.", __FUNCTION__); perror("{} nullptr.", __FUNCTION__);
return; return;
} }
switch (buf->type_) { switch (buf->type_) {
case TYPE_GET_ID: { case TYPE_GET_ID: {
logger_->debug("Your ID:{}", buf->tid_); pdebug("Your ID:{}", buf->tid_);
own_id_ = buf->tid_; own_id_ = buf->tid_;
break; break;
} }
@ -500,9 +498,9 @@ void CClient::handle_frame(CFrameBuffer* buf)
} }
if (real.find("[") == std::string::npos) { if (real.find("[") == std::string::npos) {
#ifdef _WIN32 #ifdef _WIN32
logger_->info("FILE ==> {}", CCodec::u8_to_ansi(real)); pinfo("FILE ==> {}", CCodec::u8_to_ansi(real));
#else #else
logger_->info("FILE ==> {}", real); pinfo("FILE ==> {}", real);
#endif #endif
task_list_[index]->files.push_back(real); task_list_[index]->files.push_back(real);
} else { } else {
@ -522,8 +520,8 @@ void CClient::handle_frame(CFrameBuffer* buf)
task_list_[index]->id = id; task_list_[index]->id = id;
} }
logger_->debug("*****************************************"); pdebug("*****************************************");
logger_->info("{}", real); pinfo("{}", real);
} }
} }
break; break;
@ -538,7 +536,7 @@ void CClient::handle_frame(CFrameBuffer* buf)
down_->file_.write(buf->data_, buf->len_); down_->file_.write(buf->data_, buf->len_);
if (down_->file_.fail()) { if (down_->file_.fail()) {
report_trans_ret(TRANS_FAILED); report_trans_ret(TRANS_FAILED);
logger_->warn("no matched write and data. {}", buf->len_); pwarn("no matched write and data. {}", buf->len_);
} }
cur_down_size_ += buf->len_; cur_down_size_ += buf->len_;
} }
@ -557,7 +555,7 @@ void CClient::handle_frame(CFrameBuffer* buf)
up_[buf->fid_]->file_.open(up_[buf->fid_]->cur_file_, std::ios::in | std::ios::binary); up_[buf->fid_]->file_.open(up_[buf->fid_]->cur_file_, std::ios::in | std::ios::binary);
up_[buf->fid_]->trans_state_ = TRANS_REDAY; up_[buf->fid_]->trans_state_ = TRANS_REDAY;
if (!up_[buf->fid_]->file_.is_open()) { if (!up_[buf->fid_]->file_.is_open()) {
logger_->error("Ready Send File {} Open Failed.", up_[buf->fid_]->cur_file_); perror("Ready Send File {} Open Failed.", up_[buf->fid_]->cur_file_);
break; break;
} }
keys = buf->fid_; keys = buf->fid_;
@ -575,7 +573,7 @@ void CClient::handle_frame(CFrameBuffer* buf)
if (buf->mark_) { if (buf->mark_) {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (!up_.count(buf->fid_)) { if (!up_.count(buf->fid_)) {
logger_->warn("Offline no match."); pwarn("Offline no match.");
break; break;
} }
auto t = up_[buf->fid_]; auto t = up_[buf->fid_];
@ -583,7 +581,7 @@ void CClient::handle_frame(CFrameBuffer* buf)
break; break;
} }
if (downloading_ && !down_->cur_remote_file_.empty()) { if (downloading_ && !down_->cur_remote_file_.empty()) {
logger_->warn("Stop Down {} From {}.", down_->cur_remote_file_, buf->fid_); pwarn("Stop Down {} From {}.", down_->cur_remote_file_, buf->fid_);
} }
report_trans_ret(TRANS_FAILED); report_trans_ret(TRANS_FAILED);
break; break;
@ -599,14 +597,14 @@ void CClient::handle_frame(CFrameBuffer* buf)
} }
std::swap(buf->tid_, buf->fid_); std::swap(buf->tid_, buf->fid_);
if (!send_frame(buf)) { if (!send_frame(buf)) {
logger_->error("Send Failed {}.", __LINE__); perror("Send Failed {}.", __LINE__);
break; break;
} }
if (buf->type_ == TYPE_UNCONFIRM_UPDATE_LIST) { if (buf->type_ == TYPE_UNCONFIRM_UPDATE_LIST) {
break; break;
} }
list_serve_id_ = buf->tid_; list_serve_id_ = buf->tid_;
logger_->debug("Do Task From {}.", buf->tid_); pdebug("Do Task From {}.", buf->tid_);
if (update_list_th_.joinable()) { if (update_list_th_.joinable()) {
update_list_th_.join(); update_list_th_.join();
} }
@ -614,26 +612,26 @@ void CClient::handle_frame(CFrameBuffer* buf)
break; break;
} }
case TYPE_CONFIRM_UPDATE_LIST: { case TYPE_CONFIRM_UPDATE_LIST: {
logger_->info("remote {} check {} passed!", buf->fid_, list_file_); pinfo("remote {} check {} passed!", buf->fid_, list_file_);
break; break;
} }
case TYPE_UNCONFIRM_UPDATE_LIST: { case TYPE_UNCONFIRM_UPDATE_LIST: {
logger_->error("remote {} check {} not passed!", buf->fid_, list_file_); perror("remote {} check {} not passed!", buf->fid_, list_file_);
break; break;
} }
case TYPE_DONE_UPDATE_LIST: { case TYPE_DONE_UPDATE_LIST: {
logger_->info("remote {} do task {} success!", buf->fid_, list_file_); pinfo("remote {} do task {} success!", buf->fid_, list_file_);
break; break;
} }
case TYPE_FAILED_UPDATE_LIST: { case TYPE_FAILED_UPDATE_LIST: {
logger_->info("remote {} do task {} failed!", buf->fid_, list_file_); pinfo("remote {} do task {} failed!", buf->fid_, list_file_);
break; break;
} }
case TYPE_FILE_SIZE: { case TYPE_FILE_SIZE: {
std::string str_size(buf->data_, buf->len_); std::string str_size(buf->data_, buf->len_);
long long size = std::stoll(str_size); long long size = std::stoll(str_size);
std::string show_str = OfUtil::get_file_size(size); std::string show_str = OfUtil::get_file_size(size);
logger_->info("Ready Down Size: {}", show_str); pinfo("Ready Down Size: {}", show_str);
cur_file_size_ = size; cur_file_size_ = size;
} }
default: default:
@ -649,13 +647,13 @@ void CClient::send_file_data_th(const char* keys)
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (!up_.count(str_key)) { if (!up_.count(str_key)) {
logger_->error("{} no matched key.", __FUNCTION__); perror("{} no matched key.", __FUNCTION__);
return; return;
} }
t = up_[str_key]; t = up_[str_key];
} }
logger_->info("Start Trans File {} To {}", t->cur_file_, str_key); pinfo("Start Trans File {} To {}", t->cur_file_, str_key);
std::shared_ptr<CFrameBuffer> buf = std::make_shared<CFrameBuffer>(); std::shared_ptr<CFrameBuffer> buf = std::make_shared<CFrameBuffer>();
buf->data_ = new char[g_BuffSize]{}; buf->data_ = new char[g_BuffSize]{};
buf->tid_ = str_key; buf->tid_ = str_key;
@ -667,11 +665,11 @@ void CClient::send_file_data_th(const char* keys)
buf->type_ = TYPE_FILE_SIZE; buf->type_ = TYPE_FILE_SIZE;
std::string str_size = std::to_string(size); std::string str_size = std::to_string(size);
logger_->info("To {} File Size: {} [{}]", str_key, ofen::OfUtil::get_file_size(size), size); pinfo("To {} File Size: {} [{}]", str_key, ofen::OfUtil::get_file_size(size), size);
buf->len_ = std::snprintf(buf->data_, g_BuffSize, "%s", str_size.c_str()); buf->len_ = std::snprintf(buf->data_, g_BuffSize, "%s", str_size.c_str());
if (!send_frame(buf.get())) { if (!send_frame(buf.get())) {
report_trans_ret(TRANS_FAILED, str_key); report_trans_ret(TRANS_FAILED, str_key);
logger_->error("Stop Trans {} To {} failed.", t->cur_file_, str_key); perror("Stop Trans {} To {} failed.", t->cur_file_, str_key);
return; return;
} }
buf->type_ = TYPE_TRANS_FILE; buf->type_ = TYPE_TRANS_FILE;
@ -679,7 +677,7 @@ void CClient::send_file_data_th(const char* keys)
while (!t->file_.eof()) { while (!t->file_.eof()) {
if (t->trans_state_ == TRANS_BREAK) { if (t->trans_state_ == TRANS_BREAK) {
logger_->warn("Stop Trans {} To {} failed.", t->cur_file_, str_key); pwarn("Stop Trans {} To {} failed.", t->cur_file_, str_key);
report_trans_ret(TRANS_FAILED, str_key); report_trans_ret(TRANS_FAILED, str_key);
return; return;
} }
@ -687,7 +685,7 @@ void CClient::send_file_data_th(const char* keys)
buf->len_ = t->file_.gcount(); buf->len_ = t->file_.gcount();
if (!send_frame(buf.get())) { if (!send_frame(buf.get())) {
report_trans_ret(TRANS_FAILED, str_key); report_trans_ret(TRANS_FAILED, str_key);
logger_->error("Stop Trans {} To {} failed.", t->cur_file_, str_key); perror("Stop Trans {} To {} failed.", t->cur_file_, str_key);
return; return;
} }
// std::this_thread::sleep_for(std::chrono::milliseconds(10)); // std::this_thread::sleep_for(std::chrono::milliseconds(10));
@ -695,10 +693,10 @@ void CClient::send_file_data_th(const char* keys)
buf->type_ = TYPE_TRANS_DONE; buf->type_ = TYPE_TRANS_DONE;
if (!send_frame(buf.get())) { if (!send_frame(buf.get())) {
logger_->error("send_file_data_th send DONE failed."); perror("send_file_data_th send DONE failed.");
} }
report_trans_ret(TRANS_DONE, str_key); report_trans_ret(TRANS_DONE, str_key);
logger_->debug("Trans File {} To {} Done !!!", t->cur_file_, str_key); pdebug("Trans File {} To {} Done !!!", t->cur_file_, str_key);
} }
void CClient::hearts() void CClient::hearts()
@ -708,7 +706,7 @@ void CClient::hearts()
while (th_run_) { while (th_run_) {
sleep_.sleep(); sleep_.sleep();
if (th_run_ && !send_frame(buf.get())) { if (th_run_ && !send_frame(buf.get())) {
logger_->error("{} send failed.", __FUNCTION__); perror("{} send failed.", __FUNCTION__);
th_run_ = false; th_run_ = false;
} }
} }

View File

@ -1,4 +1,5 @@
#pragma once #pragma once
#include <filecomplete.h>
#include <fstream> #include <fstream>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
@ -7,7 +8,6 @@
#include <string> #include <string>
#include <util.h> #include <util.h>
#include <vector> #include <vector>
#include <filecomplete.h>
using namespace ofen; using namespace ofen;
struct DownClientInfo { struct DownClientInfo {
@ -35,7 +35,7 @@ constexpr int down_check_wait = 100; // millsec
class CClient class CClient
{ {
public: public:
CClient(const std::shared_ptr<spdlog::logger>& logger); CClient();
~CClient(); ~CClient();
public: public:

View File

@ -9,7 +9,7 @@ namespace fs = boost::filesystem;
namespace fs = std::filesystem; namespace fs = std::filesystem;
#endif #endif
CServerConfig::CServerConfig(std::shared_ptr<spdlog::logger>& logger) : logger_(logger) CServerConfig::CServerConfig()
{ {
} }
@ -26,7 +26,7 @@ bool CServerConfig::baseInit()
} }
SI_Error ret = ini_handle_.LoadFile(config_path_.c_str()); SI_Error ret = ini_handle_.LoadFile(config_path_.c_str());
if (ret != SI_OK) { if (ret != SI_OK) {
logger_->error("Load Ini [{}] Failed.", config_path_); perror("Load Ini [{}] Failed.", config_path_);
return false; return false;
} }
init_ = true; init_ = true;
@ -38,7 +38,7 @@ bool CServerConfig::read_ini(std::vector<TransmSet>& set)
assert(init_ == true); assert(init_ == true);
long groups = ini_handle_.GetLongValue("BASE", "GROUPS"); long groups = ini_handle_.GetLongValue("BASE", "GROUPS");
if (groups < 1) { if (groups < 1) {
logger_->error("GROUPS num < 1."); perror("GROUPS num < 1.");
return false; return false;
} }
set.clear(); set.clear();
@ -85,9 +85,9 @@ bool CServerConfig::remove_ini(long num)
if (!read_ini(set)) { if (!read_ini(set)) {
return false; return false;
} }
set.erase(std::remove_if(set.begin(), set.end(), set.erase(
[&num](const TransmSet& item) { return item.grp_id == num; }), std::remove_if(set.begin(), set.end(), [&num](const TransmSet& item) { return item.grp_id == num; }),
set.end()); set.end());
ini_handle_.Reset(); ini_handle_.Reset();
ini_handle_.SetLongValue("BASE", "GROUPS", static_cast<long>(set.size())); ini_handle_.SetLongValue("BASE", "GROUPS", static_cast<long>(set.size()));
return write_ini(set); return write_ini(set);
@ -108,7 +108,7 @@ bool CServerConfig::get_ini(const std::vector<TransmSet>& set, long num, TransmS
void CServerConfig::gen_default_ini(const std::string& path) void CServerConfig::gen_default_ini(const std::string& path)
{ {
logger_->warn("Gen Default Setting Ini in [{}].", path); pwarn("Gen Default Setting Ini in [{}].", path);
ini_handle_.LoadFile(path.c_str()); ini_handle_.LoadFile(path.c_str());
ini_handle_.SetLongValue("BASE", "GROUPS", 1); ini_handle_.SetLongValue("BASE", "GROUPS", 1);
ini_handle_.SetValue("GROUP0", "IP", "127.0.0.1"); ini_handle_.SetValue("GROUP0", "IP", "127.0.0.1");

View File

@ -23,7 +23,7 @@ struct CmdParam {
class CServerConfig class CServerConfig
{ {
public: public:
CServerConfig(std::shared_ptr<spdlog::logger>& logger); CServerConfig();
~CServerConfig(); ~CServerConfig();
public: public:
@ -41,5 +41,4 @@ private:
bool init_{false}; bool init_{false};
CSimpleIniA ini_handle_{}; CSimpleIniA ini_handle_{};
std::string config_path_{}; std::string config_path_{};
std::shared_ptr<spdlog::logger> logger_;
}; };

View File

@ -43,7 +43,7 @@ bool exec_cmd(const CmdParam& param, bool& run)
return false; return false;
} }
for (const auto& item : set) { for (const auto& item : set) {
g_Logger->info("{} => {}:{}", item.group, item.ip, item.port); pinfo("{} => {}:{}", item.group, item.ip, item.port);
} }
return true; return true;
} }
@ -52,42 +52,40 @@ bool exec_cmd(const CmdParam& param, bool& run)
return true; return true;
} }
if (!param.appendValue.empty() && !param.removeValue.empty()) { if (!param.appendValue.empty() && !param.removeValue.empty()) {
g_Logger->error("append and remove can't simultaneous operate!"); perror("append and remove can't simultaneous operate!");
return false; return false;
} }
if (!param.appendValue.empty()) { if (!param.appendValue.empty()) {
std::regex rg(R"(([^:]+):(\d+))"); std::regex rg(R"(([^:]+):(\d+))");
std::smatch match; std::smatch match;
if (!std::regex_search(param.appendValue, match, rg)) { if (!std::regex_search(param.appendValue, match, rg)) {
g_Logger->error("append invalid format!"); perror("append invalid format!");
return false; return false;
} }
std::string ip = match[1].str(); std::string ip = match[1].str();
std::string port = match[2].str(); std::string port = match[2].str();
if (!g_Config->append_ini(ip, std::stol(port))) { if (!g_Config->append_ini(ip, std::stol(port))) {
g_Logger->error("add {}:{} failed.", ip, port); perror("add {}:{} failed.", ip, port);
return false; return false;
} }
g_Logger->info("add {}:{} success.", ip, port); pinfo("add {}:{} success.", ip, port);
return true; return true;
} }
if (!param.removeValue.empty()) { if (!param.removeValue.empty()) {
if (!g_Config->remove_ini(std::stol(param.removeValue))) { if (!g_Config->remove_ini(std::stol(param.removeValue))) {
g_Logger->error("remove config num=[{}] failed, please check!", param.removeValue); perror("remove config num=[{}] failed, please check!", param.removeValue);
return false; return false;
} }
g_Logger->info("remove config num=[{}] success!", param.removeValue); pinfo("remove config num=[{}] success!", param.removeValue);
return true; return true;
} }
g_Logger->error("not matched!", param.removeValue); perror("not matched!", param.removeValue);
return false; return false;
} }
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
auto log_path = ofen::COfPath::to_full("client.log"); g_Config = std::make_shared<CServerConfig>();
g_Logger = get_logger("client", log_path);
g_Config = std::make_shared<CServerConfig>(g_Logger);
if (!g_Config->baseInit()) { if (!g_Config->baseInit()) {
return -1; return -1;
} }
@ -99,7 +97,7 @@ int main(int argc, char* argv[])
return 0; return 0;
} }
if (!exec_cmd(param, run)) { if (!exec_cmd(param, run)) {
g_Logger->error("exec_cmd failed!"); perror("exec_cmd failed!");
return -1; return -1;
} }
if (!run) { if (!run) {
@ -112,14 +110,13 @@ int main(int argc, char* argv[])
} }
TransmSet use; TransmSet use;
if (!g_Config->get_ini(set, param.use_config, use)) { if (!g_Config->get_ini(set, param.use_config, use)) {
g_Logger->error("Not found config by num:[{}]", param.use_config); perror("Not found config by num:[{}]", param.use_config);
return -1; return -1;
} }
g_Logger->info("Build At {} {} under {} on {}", __DATE__, __TIME__, VERSION_GIT_COMMIT, pinfo("Build At {} {} under {} on {}", __DATE__, __TIME__, VERSION_GIT_COMMIT, VERSION_GIT_BRANCH);
VERSION_GIT_BRANCH); pinfo("use ip => [{}], port => [{}]", use.ip, use.port);
g_Logger->info("use ip:[{}], port:[{}]", use.ip, use.port); CClient client;
CClient client(g_Logger);
client.run(use.ip, std::to_string(use.port)); client.run(use.ip, std::to_string(use.port));
g_Logger->info("exit =========="); pinfo("exit ==========");
return 0; return 0;
} }

@ -1 +1 @@
Subproject commit 569ba7232d12573bff572d71043a5fd0e03f9df0 Subproject commit 909c68cf6e376acb975af21af7709b1129e5d0db

View File

@ -1,7 +1,6 @@
#include "net_base.h" #include "net_base.h"
CTcpClient::CTcpClient(asio::io_context& io_context, const std::shared_ptr<spdlog::logger>& logger) CTcpClient::CTcpClient(asio::io_context& io_context) : io_context_(io_context), socket_(io_context_)
: logger_(logger), io_context_(io_context), socket_(io_context_)
{ {
} }
@ -15,11 +14,11 @@ bool CTcpClient::connect(const std::string& host, const std::string& port)
asio::ip::tcp::resolver resolver(io_context_); asio::ip::tcp::resolver resolver(io_context_);
asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(host, port); asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(host, port);
asio::connect(socket_, endpoints); asio::connect(socket_, endpoints);
logger_->info("Connected to {}:{}", host, port); pinfo("Connected to {}:{}", host, port);
is_normal_ = true; is_normal_ = true;
return true; return true;
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
logger_->error("Connection failed: {}", ex.what()); perror("Connection failed: {}", ex.what());
return false; return false;
} }
} }
@ -30,9 +29,9 @@ void CTcpClient::disconnect()
try { try {
socket_.shutdown(asio::ip::tcp::socket::shutdown_both); socket_.shutdown(asio::ip::tcp::socket::shutdown_both);
socket_.close(); socket_.close();
logger_->info("Disconnected."); pinfo("Disconnected.");
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
logger_->error("Error during disconnection: {}", ex.what()); perror("Error during disconnection: {}", ex.what());
} }
} }
} }
@ -40,15 +39,15 @@ void CTcpClient::disconnect()
bool CTcpClient::send(const char* data, int len) bool CTcpClient::send(const char* data, int len)
{ {
if (!is_normal_) { if (!is_normal_) {
logger_->error("abnormal state, will not send."); perror("abnormal state, will not send.");
return false; return false;
} }
try { try {
auto send_size = asio::write(socket_, asio::buffer(data, len)); auto send_size = asio::write(socket_, asio::buffer(data, len));
// logger_->info("Need Send len: {} Real Send len: {}", len, send_size); // pinfo("Need Send len: {} Real Send len: {}", len, send_size);
return static_cast<int>(send_size) == len; return static_cast<int>(send_size) == len;
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
logger_->error("Send failed: {}", ex.what()); perror("Send failed: {}", ex.what());
return false; return false;
} }
} }
@ -69,10 +68,10 @@ void CTcpClient::async_recv()
return; return;
} }
if (ec.value() == 125) { if (ec.value() == 125) {
logger_->info("{} exit.", __FUNCTION__); pinfo("{} exit.", __FUNCTION__);
return; return;
} }
logger_->error("{} {} error => {}", __FUNCTION__, ec.value(), ec.message()); perror("{} {} error => {}", __FUNCTION__, ec.value(), ec.message());
} else { } else {
buffer_.push(tmp_buf_.data(), length); buffer_.push(tmp_buf_.data(), length);
while (true) { while (true) {

View File

@ -9,7 +9,7 @@ using namespace ofen;
class CTcpClient : public std::enable_shared_from_this<CTcpClient> class CTcpClient : public std::enable_shared_from_this<CTcpClient>
{ {
public: public:
CTcpClient(asio::io_context& io_context, const std::shared_ptr<spdlog::logger>& logger); CTcpClient(asio::io_context& io_context);
~CTcpClient(); ~CTcpClient();
public: public:
@ -21,7 +21,6 @@ public:
bool is_normal(); bool is_normal();
private: private:
std::shared_ptr<spdlog::logger> logger_;
asio::io_context& io_context_; asio::io_context& io_context_;
asio::ip::tcp::socket socket_; asio::ip::tcp::socket socket_;
std::mutex mutex_; std::mutex mutex_;

2
ofen

@ -1 +1 @@
Subproject commit 71948320b735e33db511f756b5df83ef3ddcf2c7 Subproject commit cf634e27daf2f4435fc043d372bc5202fe164766

View File

@ -1,7 +1,7 @@
#include "util.h" #include "util.h"
#include <cstdint> #include <cstdint>
#include <thread>
#include <iostream> #include <iostream>
#include <thread>
std::shared_ptr<spdlog::logger> get_logger(const std::string& mark, const std::string& log_file) std::shared_ptr<spdlog::logger> get_logger(const std::string& mark, const std::string& log_file)
{ {
@ -134,7 +134,7 @@ void CTransProtocal::display_progress(float percent)
} }
} }
// \r 回到行首 // \r 回到行首
std::cout << "] " << int(percent * 100.0f) << " %\r"; std::cout << "] " << int(percent * 100.0f) << " %\r";
std::cout.flush(); std::cout.flush();
} }

View File

@ -1,7 +1,11 @@
#pragma once #pragma once
#include "of_util.h" #include "of_util.h"
#include <chrono>
#include <cstdint> #include <cstdint>
#include <functional> #include <functional>
#include <iomanip>
#include <spdlog/fmt/bundled/color.h>
#include <spdlog/fmt/fmt.h>
#include <spdlog/sinks/rotating_file_sink.h> #include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
@ -74,3 +78,33 @@ public:
static bool pack(CFrameBuffer* buf, char** out_buf, int& len); static bool pack(CFrameBuffer* buf, char** out_buf, int& len);
static void display_progress(float percent); static void display_progress(float percent);
}; };
inline std::string now_str()
{
auto now = std::chrono::system_clock::now();
auto time_t_now = std::chrono::system_clock::to_time_t(now);
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
std::ostringstream timestamp;
timestamp << std::put_time(std::localtime(&time_t_now), "[%Y-%m-%d %H:%M:%S") << "." << std::setfill('0')
<< std::setw(3) << milliseconds.count() << "] ";
return timestamp.str();
}
template <typename... Args> void pdebug(const std::string& format, Args&&... args)
{
fmt::print(fg(fmt::color::steel_blue), now_str() + format + "\n", std::forward<Args>(args)...);
}
template <typename... Args> void pinfo(const std::string& format, Args&&... args)
{
fmt::print(fg(fmt::color::gray), now_str() + format + "\n", std::forward<Args>(args)...);
}
template <typename... Args> void pwarn(const std::string& format, Args&&... args)
{
fmt::print(fg(fmt::color::yellow_green), now_str() + format + "\n", std::forward<Args>(args)...);
}
template <typename... Args> void perror(const std::string& format, Args&&... args)
{
fmt::print(fg(fmt::color::orange_red), now_str() + format + "\n", std::forward<Args>(args)...);
}