tdaq-develop-2025-02-12
TCPServerBase.h
1 #ifndef _ots_TCPServerBase_h_
2 #define _ots_TCPServerBase_h_
3 
4 #include <future>
5 #include <map>
6 #include <string>
7 #include <vector>
8 // #include <thread>
9 #include <atomic>
10 #include "otsdaq/NetworkUtilities/TCPSocket.h"
11 
12 namespace ots
13 {
14 class TCPServerBase : public virtual TCPSocket
15 {
16  public:
17  TCPServerBase(unsigned int serverPort,
18  unsigned int maxNumberOfClients = 0);
19  virtual ~TCPServerBase(void);
20 
21  void startAccept(void);
22  void broadcastPacket(const char* message, std::size_t length);
23  void broadcastPacket(const std::string& message);
24  void broadcast(const char* message, std::size_t length);
25  void broadcast(const std::string& message);
26  void broadcast(const std::vector<char>& message);
27  void broadcast(const std::vector<uint16_t>& message);
28 
29  protected:
30  virtual void acceptConnections() = 0;
31 
32  void closeClientSocket(int socket);
33  template<class T>
34  T* acceptClient(bool blocking = true)
35  {
36  int socketId = accept(blocking);
37  fConnectedClients.emplace(socketId, new T(socketId));
38  return dynamic_cast<T*>(fConnectedClients[socketId]);
39  }
40 
41  void pingActiveClients(void);
42 
43  // std::promise<bool> fAcceptPromise;
44  std::map<int, TCPSocket*> fConnectedClients;
45  std::map<int, std::future<void>> fConnectedClientsFuture;
46  const int E_SHUTDOWN = 0;
47  bool getAccept() { return fAccept.load(); }
48 
49  private:
50  void closeClientSockets(
51  void);
52  int accept(bool blocking = true);
53  void shutdownAccept(void);
54 
55  const int fMaxConnectionBacklog = 5;
56  unsigned int fMaxNumberOfClients;
57  unsigned int fServerPort;
58  std::atomic_bool fAccept;
59  // std::thread fAcceptThread;
60  std::future<void> fAcceptFuture;
61 };
62 } // namespace ots
63 
64 #endif
TCPServerBase(unsigned int serverPort, unsigned int maxNumberOfClients=0)
Means as many unsigned allows.