Server.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <utility>
  2. #include "network/Server.h"
  3. Server::Client::Client(ENetPeer* peer, int id) : peer(peer), id(id) {
  4. }
  5. Server::Client::~Client() {
  6. if(peer != nullptr) {
  7. enet_peer_disconnect(peer, 0);
  8. }
  9. }
  10. Server::Client::Client(Client&& other) : Client(nullptr, -1) {
  11. std::swap(peer, other.peer);
  12. std::swap(id, other.id);
  13. }
  14. Server::Client& Server::Client::operator=(Client&& other) {
  15. std::swap(peer, other.peer);
  16. std::swap(id, other.id);
  17. return *this;
  18. }
  19. int Server::Client::getId() const {
  20. return id;
  21. }
  22. void Server::Client::send(OutPacket& p) {
  23. if(p.packet != nullptr) {
  24. p.packet->dataLength = p.index;
  25. enet_peer_send(peer, p.channel, p.packet);
  26. p.packet = nullptr;
  27. }
  28. }
  29. Server::Server(Port port, int maxClients) : server(nullptr), idCounter(1) {
  30. ENetAddress address;
  31. address.host = ENET_HOST_ANY;
  32. address.port = port;
  33. server = enet_host_create(&address, maxClients, 3, 0, 0);
  34. if(server == nullptr) {
  35. error.clear().append("cannot create ENet server host");
  36. }
  37. }
  38. Server::~Server() {
  39. for(auto& client : clients) {
  40. enet_peer_reset(client.value.peer);
  41. }
  42. enet_host_destroy(server);
  43. }
  44. bool Server::hasError() const {
  45. return error.getLength() > 0;
  46. }
  47. const Server::Error& Server::getError() const {
  48. return error;
  49. }
  50. void Server::send(OutPacket& p) {
  51. if(p.packet != nullptr) {
  52. p.packet->dataLength = p.index;
  53. enet_host_broadcast(server, p.channel, p.packet);
  54. p.packet = nullptr;
  55. }
  56. }
  57. void Server::disconnect(Client& client) {
  58. enet_peer_reset(client.peer);
  59. clients.remove(client.getId());
  60. }