mesytec-mnode/src/mnode_proto_ping_client.cc

94 lines
2.4 KiB
C++
Raw Normal View History

#include <atomic>
2024-12-07 16:12:40 +01:00
#include <memory>
#include <mesytec-mvlc/mesytec-mvlc.h>
#include <mesytec-mvlc/util/signal_handling.h>
#include "proto/service.pb.h"
#include <mesytec-mnode/mnode_nng_async.h>
2024-12-07 16:12:40 +01:00
using namespace mesytec;
2024-12-07 16:48:24 +01:00
using namespace mesytec::mnode;
2024-12-07 16:12:40 +01:00
using namespace std::literals;
class PingClient: public nng::AsyncReqWork
2024-12-07 16:12:40 +01:00
{
public:
explicit PingClient(nng_socket socket)
: AsyncReqWork(socket)
2024-12-07 16:12:40 +01:00
{
}
nng::unique_msg make_request() override
2024-12-07 16:12:40 +01:00
{
ping_.set_peer_id(peer_id);
ping_.set_sequence_number(sequence_number++);
return nng::make_message(ping_.SerializeAsString());
2024-12-07 16:12:40 +01:00
}
void handle_reply(nng::unique_msg &&request, nng::unique_msg &&reply) override
2024-12-07 16:12:40 +01:00
{
ping_.ParseFromArray(nng_msg_body(request.get()), nng_msg_len(request.get()));
pong_.ParseFromArray(nng_msg_body(reply.get()), nng_msg_len(reply.get()));
2024-12-07 16:12:40 +01:00
if (ping_.sequence_number() != pong_.sequence_number())
spdlog::error("Work: sequence_number mismatch: ping={}, pong={}",
ping_.sequence_number(), pong_.sequence_number());
2024-12-07 16:12:40 +01:00
if (ping_.peer_id() != pong_.peer_id())
spdlog::error("Work: peer_id mismatch: ping={}, pong={}", ping_.peer_id(),
pong_.peer_id());
2024-12-07 16:12:40 +01:00
++num_transactions;
2024-12-07 16:12:40 +01:00
}
void report()
{
spdlog::info("PingClient, peer_id={}, transactions={}", peer_id, num_transactions);
2024-12-07 16:12:40 +01:00
}
private:
proto::Ping ping_;
proto::Pong pong_;
size_t sequence_number = 1;
static std::atomic<size_t> next_peer_id;
size_t peer_id = next_peer_id++;
size_t num_transactions = 0;
2024-12-07 16:12:40 +01:00
};
std::atomic<size_t> PingClient::next_peer_id;
2024-12-07 16:12:40 +01:00
int main()
{
spdlog::set_level(spdlog::level::info);
auto socket = nng::make_req_socket(1000);
2024-12-07 16:12:40 +01:00
if (int res = nng_dial(socket, "tcp://localhost:5555", nullptr, NNG_FLAG_NONBLOCK))
2024-12-07 16:12:40 +01:00
{
2024-12-07 17:36:59 +01:00
nng::mnode_nng_error("nng_dial", res);
2024-12-07 16:12:40 +01:00
return res;
}
mvlc::util::Stopwatch sw;
std::vector<std::unique_ptr<PingClient>> clients;
for (int i = 0; i < 10; ++i)
clients.emplace_back(std::make_unique<PingClient>(socket));
for (auto &client: clients)
client->work();
2024-12-07 16:12:40 +01:00
for (;;)
{
nng_msleep(100);
if (sw.get_interval() >= 1s)
{
for (auto &client: clients)
client->report();
2024-12-07 16:12:40 +01:00
sw.interval();
}
}
return 0;
}