GameServer.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "server/GameServer.h"
  2. #include "common/network/Packets.h"
  3. #include "memory/UniquePointer.h"
  4. #include "server/Game.h"
  5. #include "utils/Logger.h"
  6. static Server server;
  7. static HashMap<int, UniquePointer<ServerPlayer>> players;
  8. static void handleControllerPacket(ServerPlayer& p, InPacket& in) {
  9. PlayerUpdatePacket pup;
  10. pup.read(in);
  11. p.onUpdatePacket(pup);
  12. }
  13. struct Receiver {
  14. void onConnect(Server::Client& client) {
  15. if(players.tryEmplace(client.getId(), new ServerPlayer(client))) {
  16. LOG_WARNING(StringBuffer<50>("cannot emplace client id: ")
  17. .append(client.getId()));
  18. server.disconnect(client);
  19. return;
  20. }
  21. auto* p = players.search(client.getId());
  22. if(p == nullptr) {
  23. LOG_WARNING("cannot find added client");
  24. return;
  25. }
  26. Game::addPlayer(**p);
  27. }
  28. void onDisconnect(Server::Client& client) {
  29. auto* p = players.search(client.getId());
  30. if(p == nullptr) {
  31. LOG_WARNING("disconnecting missing player");
  32. return;
  33. }
  34. Game::removePlayer(**p);
  35. players.remove(client.getId());
  36. }
  37. void onPacket(Server::Client& client, InPacket& in) {
  38. auto* p = players.search(client.getId());
  39. if(p == nullptr) {
  40. LOG_WARNING("packet from missing player");
  41. return;
  42. }
  43. uint16 id;
  44. if(in.readU16(id)) {
  45. LOG_WARNING("invalid packet from client without id");
  46. return;
  47. }
  48. switch(id) {
  49. case Packets::C_CHAT: (*p)->onChat(in); break;
  50. case Packets::C_PLAYER_UPDATE:
  51. handleControllerPacket(**p, in);
  52. break;
  53. default: LOG_WARNING("invalid packet from client with unknown id");
  54. }
  55. }
  56. };
  57. bool GameServer::init(Server::Port port, int maxClients) {
  58. Error error = server.start(port, maxClients);
  59. if(error.has()) {
  60. LOG_ERROR(error.message);
  61. }
  62. return error.has();
  63. }
  64. void GameServer::tick() {
  65. Receiver r;
  66. server.consumeEvents(r);
  67. }
  68. void GameServer::sendToAll(OutPacket& out) {
  69. server.send(out);
  70. }