SimpleAI
 All Classes Namespaces Files Functions Variables Typedefs Macros Groups Pages
Network.h
Go to the documentation of this file.
1 
4 #pragma once
5 
6 #include "IProtocolHandler.h"
7 #include "common/Thread.h"
8 #include <string>
9 #include <stdint.h>
10 #include <list>
11 #ifdef WIN32
12 #define NOMINMAX
13 #include <winsock2.h>
14 #include <ws2tcpip.h>
15 #include <ws2spi.h>
16 #else
17 #define SOCKET int
18 #include <sys/select.h>
19 #endif
20 
21 namespace ai {
22 
23 class IProtocolMessage;
24 
25 struct Client {
26  explicit Client(SOCKET _socket) :
27  socket(_socket), finished(false), in(), out() {
28  }
29  SOCKET socket;
30  bool finished;
31  streamContainer in;
32  streamContainer out;
33 };
34 
36 public:
37  virtual ~INetworkListener() {}
38 
39  virtual void onConnect(Client*) {}
40  virtual void onDisconnect(Client*) {}
41 };
42 
43 class Network {
44 protected:
45  uint16_t _port;
46  std::string _hostname;
47  // the socket file descriptor
48  SOCKET _socketFD;
49  fd_set _readFDSet;
50  fd_set _writeFDSet;
51  int64_t _time;
52 
53  typedef std::list<Client> ClientSockets;
54  typedef ClientSockets::iterator ClientSocketsIter;
55  ClientSockets _clientSockets;
56  ClientSocketsIter closeClient (ClientSocketsIter& i);
57 
58  typedef std::list<INetworkListener*> Listeners;
59  Listeners _listeners;
60 
61  bool sendMessage(Client& client);
62 public:
63  Network(uint16_t port = 10001, const std::string& hostname = "0.0.0.0");
64  virtual ~Network();
65 
66  bool start();
67  void update(int64_t deltaTime);
68 
69  void addListener(INetworkListener* listener);
70  void removeListener(INetworkListener* listener);
71 
72  int getConnectedClients() const;
73 
77  bool broadcast(const IProtocolMessage& msg);
78  bool sendToClient(Client* client, const IProtocolMessage& msg);
79 };
80 
81 inline int Network::getConnectedClients() const {
82  return static_cast<int>(_clientSockets.size());
83 }
84 
85 inline void Network::addListener(INetworkListener* listener) {
86  _listeners.push_back(listener);
87 }
88 
89 inline void Network::removeListener(INetworkListener* listener) {
90  _listeners.remove(listener);
91 }
92 
93 }
Definition: Network.h:35
A protocol message is used for the serialization of the ai states for remote debugging.
Definition: IProtocolMessage.h:60
bool broadcast(const IProtocolMessage &msg)
Definition: NetworkImpl.h:230
Definition: Network.h:43
Definition: Network.h:25