#ifndef SHARED_NET_CONNECTION_HH_ #define SHARED_NET_CONNECTION_HH_ #include #include #include #include #include #include #include "shared/net/net.hh" #include "shared/net/packet.hh" #include "shared/net/proto.hh" namespace shared { namespace net { using socket_t = int; class connection { public: using upacket_t = std::shared_ptr; using rpacket_t = std::shared_ptr; private: static constexpr std::size_t MAX_PACKET_SIZE = 65536; struct sockets { socket_t rsock; socket_t usock; // connected in constructor std::string address; std::string port; }; std::optional socks; std::optional bad_reason; std::list upackets; std::list rpackets; private: bool maybe_send(const packet& packet, const socket_t& sock) noexcept; public: connection(const socket_t& rsock); // requires connected rsocket connection(const connection&) = delete; connection(connection&& other) noexcept; connection& operator=(connection&& other) noexcept; ~connection() noexcept; public: bool good() const noexcept { return !bad_reason.has_value() && this->socks.has_value(); } std::string get_bad_reason() const noexcept { return *this->bad_reason; } std::string get_address() const noexcept { return this->socks->address; } public: // When an identical packet is sent to multiple people, the functions using // rpacket_t should be used to avoid unnecessary compression. void rsend_packet(const rpacket_t& packet) noexcept; void usend_packet(const upacket_t& packet) noexcept; void rsend_packet(rpacket&& packet) noexcept; void usend_packet(upacket&& packet) noexcept; public: std::optional rrecv_packet() noexcept; std::optional urecv_packet() noexcept; std::optional recv_packet() noexcept; // from either public: void poll(); // call to send potentially queued packets void close(); // call to close sockets }; } // namespace net } // namespace shared #endif