Server.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. enet_peer_send(peer, p.channel, p.packet);
  25. p.packet = nullptr;
  26. }
  27. }
  28. Server::Server(Port port, int maxClients) : server(nullptr), idCounter(1) {
  29. ENetAddress address;
  30. address.host = ENET_HOST_ANY;
  31. address.port = port;
  32. server = enet_host_create(&address, maxClients, 3, 0, 0);
  33. if(server == nullptr) {
  34. error.clear().append("cannot create ENet server host");
  35. }
  36. }
  37. Server::~Server() {
  38. for(auto& client : clients) {
  39. enet_peer_reset(client.value.peer);
  40. }
  41. enet_host_destroy(server);
  42. }
  43. bool Server::hasError() const {
  44. return error.getLength() > 0;
  45. }
  46. const Server::Error& Server::getError() const {
  47. return error;
  48. }
  49. void Server::send(OutPacket& p) {
  50. if(p.packet != nullptr) {
  51. enet_host_broadcast(server, p.channel, p.packet);
  52. p.packet = nullptr;
  53. }
  54. }
  55. void Server::disconnect(Client& client) {
  56. enet_peer_reset(client.peer);
  57. clients.remove(client.getId());
  58. }