Select Git revision
receiver.cpp
-
Simon Oehrl authoredSimon Oehrl authored
receiver.cpp 1.51 KiB
#include <asio.hpp>
#include <asio/buffer.hpp>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <optional>
using udp = asio::ip::udp;
using clk = std::chrono::steady_clock;
class Receiver {
public:
Receiver(std::uint16_t port)
: socket(context, udp::endpoint(udp::v4(), port)) {
receive();
}
void run() { context.run(); }
private:
asio::io_context context;
udp::socket socket;
std::array<std::byte, 1024> data;
std::optional<clk::time_point> first_receive;
std::uint64_t bytes_received = 0;
clk::time_point last_print;
void receive() {
socket.async_receive(asio::buffer(data), [this](std::error_code ec,
std::size_t bytes_recvd) {
if (ec) {
std::cerr << ec.category().name() << ": " << ec.message() << std::endl;
} else {
bytes_received += bytes_recvd;
if (!first_receive.has_value()) {
first_receive = last_print = clk::now();
} else {
const auto dt = clk::now() - *first_receive;
const auto seconds =
std::chrono::duration_cast<std::chrono::duration<double>>(dt)
.count();
if (clk::now() - last_print > std::chrono::seconds(2)) {
std::cout << bytes_received * 8 / seconds / 1000.0 / 1000.0 << " Mbit/s" << std::endl;
last_print = clk::now();
}
}
this->receive();
}
});
}
};
int main(int argc, char *argv[]) {
Receiver r(std::stoi(argv[1]));
r.run();
}