Client.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. memset(&address, 0, sizeof(ENetAddress));
  27. ENetEvent event;
  28. enet_address_set_host(&address, server);
  29. address.port = port;
  30. connection = enet_host_connect(client, &address, 3, 0);
  31. if(connection == nullptr) {
  32. return {"server is not available"};
  33. }
  34. if(enet_host_service(client, &event, timeout) <= 0 ||
  35. event.type != ENET_EVENT_TYPE_CONNECT) {
  36. disconnect();
  37. return {"connection failed"};
  38. }
  39. return {};
  40. }
  41. void Client::disconnect() {
  42. if(connection == nullptr) {
  43. return;
  44. }
  45. ENetEvent e;
  46. enet_peer_disconnect(connection, 0);
  47. while(enet_host_service(client, &e, 3000) > 0) {
  48. switch(e.type) {
  49. case ENET_EVENT_TYPE_RECEIVE: enet_packet_destroy(e.packet); break;
  50. case ENET_EVENT_TYPE_DISCONNECT: connection = nullptr; return;
  51. default: break;
  52. }
  53. }
  54. enet_peer_reset(connection);
  55. connection = nullptr;
  56. }
  57. void Client::send(OutPacket& p) {
  58. assert(client != nullptr);
  59. if(p.packet != nullptr) {
  60. p.packet->dataLength = p.index;
  61. enet_peer_send(connection, p.channel, p.packet);
  62. p.packet = nullptr;
  63. }
  64. }