Client.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #ifndef CLIENT_H
  2. #define CLIENT_H
  3. #include "network/ENet.h"
  4. #include "network/Packet.h"
  5. #include "utils/StringBuffer.h"
  6. class Client final {
  7. typedef enet_uint16 Port;
  8. typedef StringBuffer<256> Error;
  9. private:
  10. ENetHost* client;
  11. ENetPeer* connection;
  12. Error error;
  13. public:
  14. Client();
  15. Client(const Client&) = delete;
  16. Client(Client&&) = delete;
  17. ~Client();
  18. Client& operator=(const Client&) = delete;
  19. Client& operator=(Client&&) = delete;
  20. bool hasError() const;
  21. const Error& getError() const;
  22. bool connect(const char* server, Port port, int timeout);
  23. void disconnect();
  24. template<typename T>
  25. void consumeEvents(T& consumer) {
  26. ENetEvent e;
  27. while(enet_host_service(client, &e, 0) > 0) {
  28. switch(e.type) {
  29. case ENET_EVENT_TYPE_CONNECT: break;
  30. case ENET_EVENT_TYPE_DISCONNECT_TIMEOUT:
  31. case ENET_EVENT_TYPE_DISCONNECT: consumer.onDisconnect(); break;
  32. case ENET_EVENT_TYPE_NONE: return;
  33. case ENET_EVENT_TYPE_RECEIVE:
  34. InPacket in(e.packet);
  35. consumer.onPacket(in);
  36. enet_packet_destroy(e.packet);
  37. break;
  38. }
  39. }
  40. }
  41. void send(OutPacket& p);
  42. };
  43. #endif