libhv/include/libhv_client_tcp.hpp

99 lines
2.8 KiB
C++

#pragma once
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include "common.h"
#include "hv/TcpClient.h"
#include "hv/htime.h"
class HvClient {
public:
void Log(const std::string &str) {
std::string log = gxt::format("[CLIENT](server{}:{}): ", ip_, port_);
std::cout << log << str << std::endl;
}
HvClient(const std::string &ip, int port,
std::function<void(std::string &)> fun = {}) {
ip_ = ip;
port_ = port;
client_ = std::make_unique<hv::TcpClient>();
int connfd = client_->createsocket(port, ip.c_str());
if (connfd < 0) {
printf("create socket error");
return;
}
// 用来设置成功连接后执行的内容,例如一直打印心跳确保连接
client_->onConnection = [&](const hv::SocketChannelPtr &channel) {};
// client_->onConnection = [](const SocketChannelPtr &channel) {
// std::string peeraddr = channel->peeraddr();
// if (channel->isConnected()) {
// printf("%s connected! connfd=%d\n", peeraddr.c_str(), channel->fd());
// setInterval(3000, [channel](TimerID timerID) {
// if (channel->isConnected()) {
// char str[DATETIME_FMT_BUFLEN] = {0};
// datetime_t dt = datetime_now();
// datetime_fmt(&dt, str);
// channel->write(str);
// } else {
// killTimer(timerID);
// }
// });
// } else {
// printf("%s disconnected! connfd=%d\n", peeraddr.c_str(),
// channel->fd());
// }
// };
// client_->onMessage = [&](const SocketChannelPtr &channel, Buffer *buf) {
// OnMessage(channel, buf);
// };
client_->onMessage = [&, fun](const hv::SocketChannelPtr &channel,
hv::Buffer *buf) {
if (fun) {
std::string msg((char *)buf->data());
fun(msg);
} else {
OnMessage(channel, buf);
}
};
// 客户端写入完成时的内容
client_->onWriteComplete = [&](const hv::SocketChannelPtr &channel,
hv::Buffer *buf) {
std::string_view msg((char *)buf->data());
Log("onWriteComplete");
};
reconn_setting_t reconn;
reconn_setting_init(&reconn);
reconn.min_delay = 1000;
reconn.max_delay = 10000;
reconn.delay_policy = 2;
client_->setReconnect(&reconn);
// 设置加密通信
// client_->withTLS();
client_->start();
}
void Send(const std::string &msg) { client_->send(msg); }
void Stop() { client_->stop(); }
~HvClient() { client_->closesocket(); }
private:
void OnMessage(const hv::SocketChannelPtr &channel, hv::Buffer *buf) {
std::string_view msg((char *)buf->data());
}
std::string ip_;
int port_;
std::unique_ptr<hv::TcpClient> client_;
};