Client.h 1.2 KB

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