| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
#pragma once |
| 22 |
|
| 23 |
#include <cstring> |
| 24 |
#include <string> |
| 25 |
|
| 26 |
#include "Utils/Network.h" |
| 27 |
|
| 28 |
namespace Network |
| 29 |
{ |
| 30 |
class TcpConnection |
| 31 |
{ |
| 32 |
public: |
| 33 |
TcpConnection() = delete; |
| 34 |
TcpConnection& operator=(const TcpConnection&) = delete; |
| 35 |
|
| 36 |
inline TcpConnection(int socket, |
| 37 |
const struct sockaddr_storage* address = nullptr) |
| 38 |
: connectionSocket(socket), |
| 39 |
connected(socket != 0) |
| 40 |
{ |
| 41 |
if (address) |
| 42 |
{ |
| 43 |
this->address = *address; |
| 44 |
} |
| 45 |
else |
| 46 |
{ |
| 47 |
memset(&(this->address), 0, sizeof(struct sockaddr_storage)); |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
inline TcpConnection(const TcpConnection& other) |
| 52 |
: connectionSocket(other.connectionSocket), |
| 53 |
connected(other.connected), |
| 54 |
address(other.address) |
| 55 |
{ |
| 56 |
} |
| 57 |
|
| 58 |
inline ~TcpConnection() |
| 59 |
{ |
| 60 |
Terminate(); |
| 61 |
} |
| 62 |
|
| 63 |
void Terminate() const; |
| 64 |
|
| 65 |
int Send(const unsigned char* buffer, const size_t bufferLength, const int flags = 0) const; |
| 66 |
|
| 67 |
inline int Send(const char* buffer, const size_t bufferLength, const int flags = 0) const |
| 68 |
{ |
| 69 |
return Send(reinterpret_cast<const unsigned char*>(buffer), bufferLength, flags); |
| 70 |
} |
| 71 |
|
| 72 |
inline int Send(const std::string& string, const int flags = 0) const |
| 73 |
{ |
| 74 |
return Send(string.c_str(), string.size(), flags); |
| 75 |
} |
| 76 |
|
| 77 |
int Receive(unsigned char* buffer, const size_t bufferLength, const int flags = 0) const; |
| 78 |
|
| 79 |
inline int Receive(char* buffer, const size_t bufferLength, const int flags = 0) const |
| 80 |
{ |
| 81 |
return Receive(reinterpret_cast<unsigned char*>(buffer), bufferLength, flags); |
| 82 |
} |
| 83 |
|
| 84 |
bool Receive(std::string& data, const size_t maxData = 1024, const int flags = 0); |
| 85 |
|
| 86 |
int ReceiveExact(unsigned char* buffer, const size_t bufferLength, const int flags = 0) const; |
| 87 |
|
| 88 |
inline bool IsConnected() const |
| 89 |
{ |
| 90 |
return connected; |
| 91 |
} |
| 92 |
|
| 93 |
inline std::string AddressAsString() |
| 94 |
{ |
| 95 |
return Utils::Network::AddressToString(&address); |
| 96 |
} |
| 97 |
|
| 98 |
private: |
| 99 |
mutable int connectionSocket; |
| 100 |
mutable volatile bool connected; |
| 101 |
struct sockaddr_storage address; |
| 102 |
}; |
| 103 |
} |