Debian Codegraph @

Network/UdpClient.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 <string>
24 #include <thread>
25 #include <vector>
26
27 #include <sys/socket.h>
28
29 #include "Logger/Logger.h"
30 #include "Utils/Network.h"
31
32 namespace Network
33 {
34 class UdpClient
35 {
36 public:
37 UdpClient() = delete;
38 UdpClient(const UdpClient&) = delete;
39 UdpClient& operator=(const UdpClient&) = delete;
40
41 inline UdpClient(const int serverSocket,
42 const struct sockaddr_storage* clientAddress,
43 const time_t timeout = 60)
44 : run(true),
45 lastUsed(time(nullptr)),
46 timeout(timeout),
47 serverSocket(serverSocket),
48 clientAddress(*clientAddress)
49 {
50 }
51
52 virtual ~UdpClient()
53 {
54 }
55
56 inline bool IsClient(const struct sockaddr_storage* address)
57 {
58 return Utils::Network::CompareAddresses(&clientAddress, address);
59 }
60
61 inline void Update()
62 {
63 lastUsed = time(nullptr);
64 }
65
66 inline bool Terminated()
67 {
68 return !run;
69 }
70
71 inline bool TimedOut()
72 {
73 return lastUsed + timeout < time(nullptr);
74 }
75
76 virtual void Work(const unsigned char* buffer, const size_t size) = 0;
77
78
79 protected:
80 inline void Send(const unsigned char* buffer, const size_t size)
81 {
82 sendto(serverSocket, buffer, size, 0, reinterpret_cast<const struct sockaddr*>(&clientAddress), sizeof(struct sockaddr_storage));
83 }
84
85 inline void Terminate()
86 {
87 run = false;
88 }
89
90 inline std::string AddressAsString()
91 {
92 return Utils::Network::AddressToString(&clientAddress);
93 }
94
95 private:
96 volatile bool run;
97 time_t lastUsed;
98 time_t timeout;
99 const int serverSocket;
100 const struct sockaddr_storage clientAddress;
101 };
102 }