16 explicit socket(
int _sock) : sock(_sock), remote_ip() {}
17 explicit socket(
int _sock, std::string remote_ip)
18 : sock(_sock), remote_ip(remote_ip) {}
37 socket(std::string server_ip, uint16_t server_port);
45 bool is_empty()
const;
46 std::string get_self_ip();
62 int try_connect(std::string servername,
int port,
int timeout_ms = 20000);
72 bool read(
char* buffer,
size_t size);
84 ssize_t read_partial(
char* buffer,
size_t max_size);
97 bool write(
const char* buffer,
size_t size);
103 template <
typename T>
105 return write(reinterpret_cast<const char*>(&obj),
sizeof(obj));
114 template <
typename T>
116 return read(reinterpret_cast<char*>(&obj),
sizeof(obj));
121 static_assert(std::is_pod<T>::value,
122 "Can't send non-pod type over TCP");
125 fprintf(stderr,
"WARNING: Attempted to write to closed socket\n");
129 return write((
char*)&local,
sizeof(T)) && read((
char*)&remote,
sizeof(T));
134 std::unique_ptr<int, std::function<void(int*)>>
fd;
159 std::optional<socket> try_accept(
int timeout_ms);
socket()
Constructs an empty, unconnected socket.
socket(int _sock, std::string remote_ip)
bool write(const T &obj)
Convenience method for sending a single POD object (e.g.
std::unique_ptr< int, std::function< void(int *)> > fd
bool read(T &obj)
Convenience method for reading a single POD object from the socket and writing it over a local value ...
std::string get_remote_ip() const
bool exchange(T local, T &remote)