diff options
Diffstat (limited to 'include/sibs')
-rw-r--r-- | include/sibs/DirectConnection.hpp | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/include/sibs/DirectConnection.hpp b/include/sibs/DirectConnection.hpp new file mode 100644 index 0000000..8e92137 --- /dev/null +++ b/include/sibs/DirectConnection.hpp @@ -0,0 +1,83 @@ +#pragma once + +#include <stdexcept> +#include <unordered_map> +#include <functional> +#include <string> +#include <memory> +#include <thread> +#include <mutex> +#include "../types.hpp" +#include "../utils.hpp" + +struct addrinfo; + +namespace sibs +{ + class InvalidAddressException : public std::runtime_error + { + public: + InvalidAddressException(const std::string &errMsg) : std::runtime_error(errMsg) {} + }; + + class ConnectionException : public std::runtime_error + { + public: + ConnectionException(const std::string &errMsg) : std::runtime_error(errMsg) {} + }; + + class SendException : public std::runtime_error + { + public: + SendException(const std::string &errMsg) : std::runtime_error(errMsg) {} + }; + + class Ipv4 + { + DISABLE_COPY(Ipv4) + public: + // Throws InvalidAddressException on error + Ipv4(const char *ip, u16 port); + ~Ipv4(); + + struct addrinfo *address; + }; + + enum class PubSubConnectResult + { + OK, + ERROR + }; + + using PubSubConnectCallback = std::function<void(PubSubConnectResult result, const std::string &resultStr)>; + using PubSubReceiveDataCallback = std::function<void(const void *data, const usize size)>; + + struct DirectConnectionPeer + { + int socket; + PubSubReceiveDataCallback receiveDataCallbackFunc; + }; + + class DirectConnections + { + DISABLE_COPY(DirectConnections) + public: + DirectConnections(u16 port = 27137); + ~DirectConnections(); + + // Throws ConnectionException on error + std::shared_ptr<DirectConnectionPeer> connect(const Ipv4 &address, PubSubReceiveDataCallback receiveDataCallbackFunc); + // Throws SendException on error + void send(const std::shared_ptr<DirectConnectionPeer> &peer, const void *data, const usize size); + private: + void receiveData(); + bool receiveDataFromPeer(const int socket, char *output); + private: + u16 port; + int eid; + std::unordered_map<int, std::shared_ptr<DirectConnectionPeer>> peers; + std::thread receiveDataThread; + std::mutex peersMutex; + bool alive; + }; +} |