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