Server.cpp 1.8 KB

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