Grail (C++)  1.4.0
A multi-platform, modular, universal engine for embedding advanced AI in games.
TCPServer.h
1 // Copyright QED Software 2023.
2 
3 #ifndef GRAIL_TCPSERVER_H
4 #define GRAIL_TCPSERVER_H
5 
6 #include "Crc16.h"
7 #include "DataType.h"
8 #include "../libs/poco/Net/include/Poco/Net/SocketAddress.h"
9 #include "../libs/poco/Net/include/Poco/Net/SocketStream.h"
10 #include "../libs/poco/Net/include/Poco/Net/StreamSocket.h"
11 #include "../libs/poco/Net/include/Poco/Net/TCPServer.h"
12 
13 #include <functional>
14 #include <memory>
15 #include <mutex>
16 #include <thread>
17 
18 namespace grail
19 {
20 namespace live
21 {
22  class TCPServer
23  {
24  public:
25  TCPServer(Poco::UInt16 port);
26  ~TCPServer();
27 
28  void Start();
29  void Stop();
30  void SendToAll(const std::string& data);
31  void SendToAll(const uint8_t* data, std::size_t dataSize, DataType dataType);
32 
33  void AddEventOnConnection(std::function<void()> event);
34 
35  bool IsAnyConnected() const;
36 
37  private:
38  void AcceptConnections();
39  void CheckDisconnects();
40 
41  constexpr static const Poco::Int32 MAGIC = 0x22669977;
42  const std::string STREAM_MAGIC;
43  const Crc16 crc;
44 
45  std::atomic<bool> isWorking{false};
46  Poco::UInt16 port;
47  std::unique_ptr<Poco::Net::ServerSocket> server;
48  std::unique_ptr<std::thread> connectionAcceptorThread = nullptr;
49  std::unique_ptr<std::thread> disconnectCheckerThread = nullptr;
50  std::vector<Poco::Net::StreamSocket> clients{};
51  std::vector<std::function<void()>> onClientConnected{};
52 
53  mutable std::mutex clientsMutex{};
54  std::mutex eventMutex{};
55  std::mutex stateChangeMutex{};
56  };
57 }
58 }
59 
60 #endif // GRAIL_TCPSERVER_H
grail::live::TCPServer
Definition: TCPServer.h:22
grail::live::Crc16
Definition: Crc16.h:14