Client.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <cassert>
  2. #include "network/Client.h"
  3. Client::Client() : client(nullptr), connection(nullptr) {
  4. ENet::add();
  5. }
  6. Client::~Client() {
  7. disconnect();
  8. enet_host_destroy(client);
  9. ENet::remove();
  10. }
  11. Error Client::start() {
  12. assert(client == nullptr);
  13. if(ENet::hasError()) {
  14. return {"cannot initialize enet"};
  15. }
  16. client = enet_host_create(nullptr, 1, 2, 0, 0);
  17. if(client == nullptr) {
  18. return {"cannot create enet client host"};
  19. }
  20. return {};
  21. }
  22. Error Client::connect(const char* server, Port port, int timeout) {
  23. assert(client != nullptr);
  24. assert(connection == nullptr);
  25. ENetAddress address;
  26. ENetEvent event;
  27. enet_address_set_host(&address, server);
  28. address.port = port;
  29. connection = enet_host_connect(client, &address, 3, 0);
  30. if(connection == nullptr) {
  31. return {"server is not available"};
  32. }
  33. if(enet_host_service(client, &event, timeout) <= 0 ||
  34. event.type != ENET_EVENT_TYPE_CONNECT) {
  35. disconnect();
  36. return {"connection failed"};
  37. }
  38. return {};
  39. }
  40. void Client::disconnect() {
  41. if(connection == nullptr) {
  42. return;
  43. }
  44. ENetEvent e;
  45. enet_peer_disconnect(connection, 0);
  46. while(enet_host_service(client, &e, 3000) > 0) {
  47. switch(e.type) {
  48. case ENET_EVENT_TYPE_RECEIVE: enet_packet_destroy(e.packet); break;
  49. case ENET_EVENT_TYPE_DISCONNECT: connection = nullptr; return;
  50. default: break;
  51. }
  52. }
  53. enet_peer_reset(connection);
  54. connection = nullptr;
  55. }
  56. void Client::send(OutPacket& p) {
  57. assert(client != nullptr);
  58. if(p.packet != nullptr) {
  59. p.packet->dataLength = p.index;
  60. enet_peer_send(connection, p.channel, p.packet);
  61. p.packet = nullptr;
  62. }
  63. }