otsdaq  3.11.00
TCPServerBase.h
1 #ifndef _ots_TCPServerBase_h_
2 #define _ots_TCPServerBase_h_
3 
4 #include <future>
5 #include <map>
6 #include <mutex>
7 #include <string>
8 #include <vector>
9 // #include <thread>
10 #include <atomic>
11 #include "otsdaq/NetworkUtilities/TCPSocket.h"
12 
13 namespace ots
14 {
15 class TCPServerBase : public virtual TCPSocket
16 {
17  public:
19  unsigned int serverPort,
20  unsigned int maxNumberOfClients = 0);
21  virtual ~TCPServerBase(void);
22 
23  void startAccept(void);
24  void shutdownAccept(void);
25  void broadcastPacket(const char* message, std::size_t length);
26  void broadcastPacket(const std::string& message);
27  void broadcast(const char* message, std::size_t length);
28  void broadcast(const std::string& message);
29  void broadcast(const std::vector<char>& message);
30  void broadcast(const std::vector<uint16_t>& message);
31 
32  protected:
33  virtual void acceptConnections() = 0;
34 
35  void closeClientSocket(int socket);
36  template<class T>
37  T* acceptClient(bool blocking = true)
38  {
39  int socketId = accept(blocking);
40  std::lock_guard<std::mutex> lock(fClientsMutex);
41  fConnectedClients.emplace(socketId, new T(socketId));
42  return dynamic_cast<T*>(fConnectedClients[socketId]);
43  }
44 
46  void removeClient(int socketId);
48  std::vector<int> getClientSocketIds(void) const;
49 
50  void pingActiveClients(void);
51 
52  // std::promise<bool> fAcceptPromise;
53  // fClientsMutex guards fConnectedClients. Every method that reads or modifies
54  // the map takes it (accept, broadcast, ping, close, remove, receive).
55  mutable std::mutex fClientsMutex;
56  std::map<int, TCPSocket*> fConnectedClients;
57  std::map<int, std::future<void>> fConnectedClientsFuture;
58  const int E_SHUTDOWN = 0;
59  bool getAccept() { return fAccept.load(); }
60 
61  private:
62  void closeClientSockets(
63  void);
64  int accept(bool blocking = true);
65 
66  const int fMaxConnectionBacklog = 5;
67  unsigned int fMaxNumberOfClients;
68  unsigned int fServerPort;
69  std::atomic_bool fAccept;
70  // std::thread fAcceptThread;
71  std::future<void> fAcceptFuture;
72 };
73 } // namespace ots
74 
75 #endif
TCPServerBase(unsigned int serverPort, unsigned int maxNumberOfClients=0)
Means as many unsigned allows.
void removeClient(int socketId)
Drop a client whose peer has gone away (no shutdown handshake, just close).
std::vector< int > getClientSocketIds(void) const
Snapshot of connected client socket ids, safe to call from any thread.
defines used also by OtsConfigurationWizardSupervisor