Debian Codegraph @

Network/TcpConnection.h

raw symbols SCIP
1 /*
2 RailControl - Model Railway Control Software
3
4 Copyright (c) 2017-2025 by Teddy / Dominik Mahrer - www.railcontrol.org
5
6 RailControl is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 RailControl is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with RailControl; see the file LICENCE. If not see
18 <http://www.gnu.org/licenses/>.
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 }