Client.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "network/Client.h"
  2. Client::Client()
  3. : client(enet_host_create(nullptr, 1, 2, 0, 0)), connection(nullptr) {
  4. if(client == nullptr) {
  5. error.clear().append("cannot crate ENet client host");
  6. }
  7. }
  8. Client::~Client() {
  9. disconnect();
  10. enet_host_destroy(client);
  11. }
  12. bool Client::hasError() const {
  13. return error.getLength() > 0;
  14. }
  15. const Client::Error& Client::getError() const {
  16. return error;
  17. }
  18. bool Client::connect(const char* server, Port port, int timeout) {
  19. ENetAddress address;
  20. ENetEvent event;
  21. enet_address_set_host(&address, server);
  22. address.port = port;
  23. connection = enet_host_connect(client, &address, 2, 0);
  24. if(connection == nullptr) {
  25. error.clear().append("server is not available");
  26. return true;
  27. }
  28. if(enet_host_service(client, &event, timeout) <= 0 ||
  29. event.type != ENET_EVENT_TYPE_CONNECT) {
  30. error.clear().append("connection failed");
  31. disconnect();
  32. return true;
  33. }
  34. return false;
  35. }
  36. void Client::disconnect() {
  37. if(connection == nullptr) {
  38. return;
  39. }
  40. ENetEvent e;
  41. enet_peer_disconnect(connection, 0);
  42. while(enet_host_service(client, &e, 3000) > 0) {
  43. switch(e.type) {
  44. case ENET_EVENT_TYPE_RECEIVE: enet_packet_destroy(e.packet); break;
  45. case ENET_EVENT_TYPE_DISCONNECT: connection = nullptr; return;
  46. default: break;
  47. }
  48. }
  49. enet_peer_reset(connection);
  50. connection = nullptr;
  51. }