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 shutdownAccept(void);
24  void broadcastPacket(const char* message, std::size_t length);
25  void broadcastPacket(const std::string& message);
26  void broadcast(const char* message, std::size_t length);
27  void broadcast(const std::string& message);
28  void broadcast(const std::vector<char>& message);
29  void broadcast(const std::vector<uint16_t>& message);
30 
31  protected:
32  virtual void acceptConnections() = 0;
33 
34  void closeClientSocket(int socket);
35  template<class T>
36  T* acceptClient(bool blocking = true)
37  {
38  int socketId = accept(blocking);
39  fConnectedClients.emplace(socketId, new T(socketId));
40  return dynamic_cast<T*>(fConnectedClients[socketId]);
41  }
42 
43  void pingActiveClients(void);
44 
45  // std::promise<bool> fAcceptPromise;
46  std::map<int, TCPSocket*> fConnectedClients;
47  std::map<int, std::future<void>> fConnectedClientsFuture;
48  const int E_SHUTDOWN = 0;
49  bool getAccept() { return fAccept.load(); }
50 
51  private:
52  void closeClientSockets(
53  void);
54  int accept(bool blocking = true);
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.