otsdaq  3.03.00
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:
18  unsigned int serverPort,
19  unsigned int maxNumberOfClients = 0);
20  virtual ~TCPServerBase(void);
21 
22  void startAccept(void);
23  void broadcastPacket(const char* message, std::size_t length);
24  void broadcastPacket(const std::string& message);
25  void broadcast(const char* message, std::size_t length);
26  void broadcast(const std::string& message);
27  void broadcast(const std::vector<char>& message);
28  void broadcast(const std::vector<uint16_t>& message);
29 
30  protected:
31  virtual void acceptConnections() = 0;
32 
33  void closeClientSocket(int socket);
34  template<class T>
35  T* acceptClient(bool blocking = true)
36  {
37  int socketId = accept(blocking);
38  fConnectedClients.emplace(socketId, new T(socketId));
39  return dynamic_cast<T*>(fConnectedClients[socketId]);
40  }
41 
42  void pingActiveClients(void);
43 
44  // std::promise<bool> fAcceptPromise;
45  std::map<int, TCPSocket*> fConnectedClients;
46  std::map<int, std::future<void>> fConnectedClientsFuture;
47  const int E_SHUTDOWN = 0;
48  bool getAccept() { return fAccept.load(); }
49 
50  private:
51  void closeClientSockets(
52  void);
53  int accept(bool blocking = true);
54  void shutdownAccept(void);
55 
56  const int fMaxConnectionBacklog = 5;
57  unsigned int fMaxNumberOfClients;
58  unsigned int fServerPort;
59  std::atomic_bool fAccept;
60  // std::thread fAcceptThread;
61  std::future<void> fAcceptFuture;
62 };
63 } // namespace ots
64 
65 #endif
TCPServerBase(unsigned int serverPort, unsigned int maxNumberOfClients=0)
Means as many unsigned allows.