otsdaq  v2_04_02
TCPServerBase.h
1 #ifndef _ots_TCPServerBase_h_
2 #define _ots_TCPServerBase_h_
3 
4 #include <future>
5 #include <string>
6 #include <unordered_map>
7 #include <vector>
8 #include "otsdaq/NetworkUtilities/TCPSocket.h"
9 
10 namespace ots
11 {
12 class TCPServerBase : public TCPSocket
13 {
14  public:
15  TCPServerBase(int serverPort, unsigned int maxNumberOfClients);
16  virtual ~TCPServerBase(void);
17 
18  void startAccept(void);
19  void broadcastPacket(const std::string& message);
20  void broadcast(const std::string& message);
21  void broadcast(const std::vector<char>& message);
22 
23  protected:
24  virtual void acceptConnections() = 0;
25 
26  void closeClientSocket(int socket);
27  template<class T>
28  T* acceptClient(bool blocking = true)
29  {
30  int socketId = accept(blocking);
31  fConnectedClients.emplace(socketId, new T(socketId));
32  return dynamic_cast<T*>(fConnectedClients[socketId]);
33  }
34 
35  std::promise<bool> fAcceptPromise;
36  std::unordered_map<int, TCPSocket*> fConnectedClients;
37  const int E_SHUTDOWN = 0;
38 
39  private:
40  void closeClientSockets(void);
41  int accept(bool blocking = true);
42  void shutdownAccept(void);
43 
44  const int fMaxConnectionBacklog = 5;
45  unsigned int fMaxNumberOfClients;
46  std::atomic_bool fAccept;
47  std::future<bool> fAcceptFuture;
48 };
49 }
50 
51 #endif