// Copyright 2022, Guillaume Meunier // Copyright 2022, Patrick Nicolas // SPDX-License-Identifier: BSL-1.0 #pragma once #include "wivrn_serialization.h" #include #include #include #include #include #include namespace xrt::drivers::wivrn { class socket_shutdown : public std::exception { public: const char * what() const noexcept override; }; class invalid_packet : public std::exception { public: const char * what() const noexcept override; }; template struct index_of_type { }; template struct index_of_type : std::integral_constant { }; template struct index_of_type : std::integral_constant::value> { }; static_assert(index_of_type::value == 0); static_assert(index_of_type::value == 1); class socket_base { protected: int fd = -1; socket_base() = default; socket_base(const socket_base &) = delete; socket_base(socket_base &&); ~socket_base(); public: int get_fd() const { return fd; } }; class UDP : public socket_base { public: UDP(); UDP(const UDP &) = delete; UDP(UDP &&) = default; deserialization_packet receive_raw(); void send_raw(const std::vector &data); void connect(in6_addr address, int port); void connect(in_addr address, int port); void bind(int port); void subscribe_multicast(in6_addr address); void unsubscribe_multicast(in6_addr address); void set_receive_buffer_size(int size); }; class TCP : public socket_base { std::vector buffer; std::unique_ptr mutex; void init(); public: TCP(in6_addr address, int port); TCP(in_addr address, int port); explicit TCP(int fd); TCP(const TCP &) = delete; TCP(TCP &&) = default; deserialization_packet receive_raw(); void send_raw(const std::vector &data); }; class TCPListener : public socket_base { public: TCPListener(int port); TCPListener(const TCPListener &) = delete; TCPListener(TCPListener &&) = default; std::pair accept(); }; template class typed_socket : public Socket { public: template typed_socket(Args &&...args) : Socket(std::forward(args)...) {} std::optional receive() { deserialization_packet packet = this->receive_raw(); if (packet.empty()) return {}; return packet.deserialize(); } template >> void send(const T &data) { serialization_packet p; p.serialize(data); this->send_raw(std::move(p)); } }; } // namespace xrt::drivers::wivrn