Client.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 create 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, 3, 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. }
  52. void Client::send(OutPacket& p) {
  53. if(p.packet != nullptr) {
  54. enet_peer_send(connection, p.channel, p.packet);
  55. p.packet = nullptr;
  56. }
  57. }