GameServer.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. struct Receiver {
  9. void onConnect(Server::Client& client) {
  10. if(players.tryEmplace(client.getId(), new ServerPlayer(client))) {
  11. LOG_WARNING(StringBuffer<50>("cannot emplace client id: ")
  12. .append(client.getId()));
  13. server.disconnect(client);
  14. return;
  15. }
  16. auto* p = players.search(client.getId());
  17. if(p == nullptr) {
  18. LOG_WARNING("cannot find added client");
  19. return;
  20. }
  21. Game::addPlayer(**p);
  22. }
  23. void onDisconnect(Server::Client& client) {
  24. auto* p = players.search(client.getId());
  25. if(p == nullptr) {
  26. LOG_WARNING("disconnecting missing player");
  27. return;
  28. }
  29. Game::removePlayer(**p);
  30. players.remove(client.getId());
  31. }
  32. void onPacket(Server::Client& client, InPacket& in) {
  33. auto* p = players.search(client.getId());
  34. if(p == nullptr) {
  35. LOG_WARNING("packet from missing player");
  36. return;
  37. }
  38. uint16 id;
  39. if(in.readU16(id)) {
  40. LOG_WARNING("invalid packet from client");
  41. return;
  42. }
  43. switch(id) {
  44. case C_CHAT: (*p)->onChat(in); break;
  45. default: LOG_WARNING("invalid packet from client");
  46. }
  47. }
  48. };
  49. bool GameServer::init(Server::Port port, int maxClients) {
  50. Error error = server.start(port, maxClients);
  51. if(error.has()) {
  52. LOG_ERROR(error.message);
  53. }
  54. return error.has();
  55. }
  56. void GameServer::tick() {
  57. Receiver r;
  58. server.consumeEvents(r);
  59. }
  60. void GameServer::sendToAll(OutPacket& out) {
  61. server.send(out);
  62. }