Derecho  0.9
Distributed systems toolkit for RDMA
tcp.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <functional>
4 #include <memory>
5 #include <string>
6 #include <optional>
7 
8 namespace tcp {
9 
10 struct exception {};
11 struct connection_failure : public exception {};
12 
13 class socket {
14  int sock;
15 
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) {}
19 
20  friend class connection_listener;
21  std::string remote_ip;
22 
23 public:
24 
28  socket() : sock(-1), remote_ip() {}
37  socket(std::string server_ip, uint16_t server_port);
38  socket(socket&& s);
39 
40  socket& operator=(socket& s) = delete;
41  socket& operator=(socket&& s);
42 
43  ~socket();
44 
45  bool is_empty() const;
46  std::string get_self_ip();
47  std::string get_remote_ip() const { return remote_ip; }
48 
62  int try_connect(std::string servername, int port, int timeout_ms = 20000);
63 
72  bool read(char* buffer, size_t size);
73 
84  ssize_t read_partial(char* buffer, size_t max_size);
85 
87  bool probe();
88 
97  bool write(const char* buffer, size_t size);
98 
103  template <typename T>
104  bool write(const T& obj) {
105  return write(reinterpret_cast<const char*>(&obj), sizeof(obj));
106  }
107 
114  template <typename T>
115  bool read(T& obj) {
116  return read(reinterpret_cast<char*>(&obj), sizeof(obj));
117  }
118 
119  template <class T>
120  bool exchange(T local, T& remote) {
121  static_assert(std::is_pod<T>::value,
122  "Can't send non-pod type over TCP");
123 
124  if(sock < 0) {
125  fprintf(stderr, "WARNING: Attempted to write to closed socket\n");
126  return false;
127  }
128 
129  return write((char*)&local, sizeof(T)) && read((char*)&remote, sizeof(T));
130  }
131 };
132 
134  std::unique_ptr<int, std::function<void(int*)>> fd;
135 
136 public:
142  explicit connection_listener(uint16_t port);
148  socket accept();
149 
159  std::optional<socket> try_accept(int timeout_ms);
160 };
161 } // namespace tcp
162 
socket(int _sock)
Definition: tcp.hpp:16
int sock
Definition: tcp.hpp:14
socket()
Constructs an empty, unconnected socket.
Definition: tcp.hpp:28
socket(int _sock, std::string remote_ip)
Definition: tcp.hpp:17
bool write(const T &obj)
Convenience method for sending a single POD object (e.g.
Definition: tcp.hpp:104
std::unique_ptr< int, std::function< void(int *)> > fd
Definition: tcp.hpp:134
std::string remote_ip
Definition: tcp.hpp:21
bool read(T &obj)
Convenience method for reading a single POD object from the socket and writing it over a local value ...
Definition: tcp.hpp:115
std::string get_remote_ip() const
Definition: tcp.hpp:47
bool exchange(T local, T &remote)
Definition: tcp.hpp:120