transm/client/client.cpp

86 lines
2.1 KiB
C++
Raw Normal View History

2024-12-11 23:23:48 +08:00
#include "client.h"
#include <iostream>
#include <of_str.h>
2024-12-11 23:23:48 +08:00
using namespace ofen;
2024-12-11 23:23:48 +08:00
CClient::CClient(const std::shared_ptr<spdlog::logger>& logger) : logger_(logger)
{
client_ = std::make_shared<CTcpClient>(io_context_, logger_);
supported_.push_back("GetTaskList");
2024-12-11 23:23:48 +08:00
}
CClient::~CClient()
{
}
void CClient::run()
{
if (!client_->connect("127.0.0.1", "8080")) {
logger_->info("{} connect err.", __FUNCTION__);
return;
}
client_->register_func([&](CFrameBuffer* buf) { handle_frame(buf); });
client_->async_recv();
std::thread thread([&]() { io_context_.run(); });
2024-12-11 23:23:48 +08:00
char line[512]{};
while (std::cin.getline(line, 512)) {
std::string cmd_input(line);
2024-12-11 23:23:48 +08:00
if (std::strstr(line, "end")) {
break;
}
auto vec = COfStr::split(cmd_input, " ");
if (vec.size() < 2) {
logger_->error("input's invalid format.");
continue;
}
auto cmd = vec[0];
if (cmd == "GetTaskList") {
bool ret = get_task_list();
logger_->info("exec GetTaskList Command result is:{}.", ret);
}
2024-12-11 23:23:48 +08:00
}
client_->disconnect();
thread.join();
logger_->info("{} exit.", __FUNCTION__);
}
bool CClient::get_task_list()
{
logger_->info("{} start.", __FUNCTION__);
char* send = nullptr;
int len{};
std::shared_ptr<CFrameBuffer> buf = std::make_shared<CFrameBuffer>();
buf->data_ = new char[512]{};
auto flen = std::snprintf(buf->data_, 512, "%s", gGetTaskList);
buf->len_ = flen;
buf->type_ = 199;
if (!CTransProtocal::pack(buf.get(), &send, len)) {
logger_->error("{} pack failed.", __FUNCTION__);
return false;
}
if (!client_->send(send, len)) {
return false;
}
delete[] send;
return true;
}
bool CClient::get_clients()
{
return false;
}
void CClient::handle_frame(CFrameBuffer* buf)
{
if (buf == nullptr) {
logger_->error("{} nullptr.", __FUNCTION__);
return;
}
logger_->debug("type: {}", buf->type_);
logger_->debug("len: {}", buf->len_);
if (buf->type_ == 199) {
logger_->debug("data: {}", buf->data_);
}
}