console_server.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #pragma once
  6. #include "container_types.h"
  7. #include "socket.h"
  8. #include "log.h"
  9. namespace crown
  10. {
  11. class ConsoleServer
  12. {
  13. public:
  14. /// Listens on the given @a port. If @a wait is true, this function
  15. /// blocks until a client is connected.
  16. ConsoleServer(uint16_t port, bool wait);
  17. void shutdown();
  18. void log(const char* msg, LogSeverity::Enum severity = LogSeverity::INFO);
  19. /// Collects requests from clients and processes them all.
  20. void update();
  21. /// Sends the given JSON-encoded string to all clients.
  22. void send(const char* json);
  23. private:
  24. void send(TCPSocket client, const char* message);
  25. void add_client(TCPSocket socket);
  26. ReadResult update_client(TCPSocket client);
  27. void process(TCPSocket client, const char* json);
  28. void process_ping(TCPSocket client, const char* json);
  29. void process_script(TCPSocket client, const char* json);
  30. void process_command(TCPSocket client, const char* json);
  31. private:
  32. struct Client
  33. {
  34. TCPSocket socket;
  35. void close()
  36. {
  37. socket.close();
  38. }
  39. };
  40. TCPSocket _server;
  41. Vector<Client> _clients;
  42. };
  43. /// Functions for accessing global console.
  44. namespace console_server_globals
  45. {
  46. // Creates the global console server.
  47. void init(uint16_t port, bool wait);
  48. /// Destroys the global console server.
  49. void shutdown();
  50. /// Updates the global console server.
  51. void update();
  52. /// Returns the global console server object.
  53. ConsoleServer& console();
  54. } // namespace console_server_globals
  55. } // namespace crown