-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatagram_socket.hpp
107 lines (83 loc) · 2.34 KB
/
datagram_socket.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
extern "C" {
#include <netinet/in.h>
#include <sys/un.h>
}
#include "communication_handler.hpp"
namespace ipc {
class DatagramSocket : public ICommunicationHandler {
public:
/**
* Create a new unix domain Socket.
*
* @param path Path to the socket.
* @param server Whether this socket is the server.
*/
DatagramSocket(std::string path, bool server);
/**
* Create a new internet domain Socket.
*
* @param address Internet address of the socket.
* @param port Port of the socket.
* @param server Whether this socket is the server.
*/
DatagramSocket(std::string address, std::uint16_t port, bool server);
/**
* Destructor for this object to cleanup data and close socket.
*/
~DatagramSocket() override;
bool open() override;
bool close() override;
bool is_open() const override;
bool await_data() override;
bool has_data() const override;
bool write(const IDataObject &obj) override;
std::variant<std::tuple<DataHeader, DataObject>, CommunicationError> read() override;
/**
* Path or address of the socket.
*/
const std::string &path() const { return std::get<0>(parameters_); }
/**
* Port of the socket if internet domain socket.
*/
std::optional<std::uint16_t> port() const { return std::get<1>(parameters_); }
/**
* Whether is socket is the server.
*/
bool server() const { return server_; }
/**
* Whether is socket is local.
*/
bool local() const { return unix_; }
private:
/**
* Build addresses for server and client.
*
* @return True, if addresses where build successfully.
*/
bool build_address();
/**
* Create socket server.
*
* @return True, if socket server was created successfully.
*/
bool create_server();
/**
* Create socket client.
*
* @return True, if socket client was created successfully.
*/
bool create_client();
private:
const std::tuple<std::string, std::optional<std::uint16_t>> parameters_;
std::variant<sockaddr_un, sockaddr_in> address_;
const bool server_;
const bool unix_;
int sfd_ = -1;
std::uint32_t last_id_ = 0;
std::array<std::byte, BUFFER_SIZE> buffer_{};
};
}