libhv/test/test_udp_mul_client_main.cc

73 lines
1.9 KiB
C++

#include "libhv_udp_client.h"
#include "test_struct.h"
using namespace hv;
template <typename T>
class Client {
public:
Client(int n = 1, std::function<void(const T&)> fun = nullptr)
: all_ports_n_(n), fun_(fun) {
static std::string client_ip =
MyYAMLConfig::Get()["client_ip"].as<std::string>();
static std::string client_port =
MyYAMLConfig::Get()["client_port"].as<std::string>();
int port = stoi(client_port);
clis_ = std::move(decltype(clis_)(n));
// sendto(time) every 3s
// cli.loop()->setInterval(3000, [&cli](TimerID timerID) {
// std::string str = gxt::format("{}", gxt::GetTimeUs());
// cli.sendto(str);
// });
for (int i = 0; i < n; i++) {
auto& cli = clis_.at(i);
int sockfd = cli.createsocket(port + i, client_ip.c_str());
if (sockfd < 0) {
std::terminate();
}
gDebug() << gxt::format("begin listen {}:{}", client_ip, port + i);
cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
gDebug(buf->size());
};
cli.start();
}
}
void Send(const T& val) {
clis_.at(cnt_port_).sendto(&val, sizeof(val));
cnt_port_++;
cnt_port_ = cnt_port_ % all_ports_n_;
}
private:
std::vector<UdpClient> clis_;
std::function<void(const T&)> fun_;
int all_ports_n_ = 0;
int cnt_port_ = 0;
};
int main(int argc, char* argv[]) {
static int ports = MyYAMLConfig::Get()["ports"].as<int>();
Client<TestStruct> clients(ports);
// while (true) {
// gxt::Sleep(3);
TestStruct test;
int datas_n = MyYAMLConfig::Get()["datas_n"].as<int>();
TIME_BEGIN_US();
while (datas_n--) {
auto time = gxt::GetTimeUs();
std::string time_str = std::to_string(time);
memcpy(test.time, time_str.c_str(), time_str.size());
test.time[time_str.size()] = '\0';
clients.Send(test);
// cli.sendto(&test, sizeof(test));
// gxt::SleepUs();
}
TIME_END();
// }
return 0;
}