console_server.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) 2012-2017 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 "string_types.h"
  9. #include "hash_map.h"
  10. namespace crown
  11. {
  12. /// Provides service to communicate with engine via TCP/IP.
  13. ///
  14. /// @ingroup Device
  15. class ConsoleServer
  16. {
  17. typedef void (*CommandFunction)(ConsoleServer& cs, TCPSocket client, const char* json, void* user_data);
  18. struct Command
  19. {
  20. CommandFunction function;
  21. void* user_data;
  22. };
  23. TCPSocket _server;
  24. Vector<TCPSocket> _clients;
  25. HashMap<StringId32, Command> _commands;
  26. void add_client(TCPSocket socket);
  27. void process(TCPSocket client, const char* json);
  28. public:
  29. ConsoleServer(Allocator& a);
  30. /// Listens on the given @a port. If @a wait is true, this function
  31. /// blocks until a client is connected.
  32. void listen(u16 port, bool wait);
  33. /// Shutdowns the server.
  34. void shutdown();
  35. /// Collects requests from clients and processes them all.
  36. void update();
  37. /// Sends the given JSON-encoded string to all clients.
  38. void send(const char* json);
  39. /// Sends the given JSON-encoded string to @a client.
  40. void send(TCPSocket client, const char* json);
  41. /// Sends an error message to @a client.
  42. void error(TCPSocket client, const char* msg);
  43. /// Sends a success message to @a client.
  44. void success(TCPSocket client, const char* msg);
  45. /// Registers the command @a type.
  46. void register_command(const char* type, CommandFunction cmd, void* user_data);
  47. };
  48. namespace console_server_globals
  49. {
  50. void init();
  51. void shutdown();
  52. } // namespace console_server_globals
  53. ConsoleServer* console_server();
  54. } // namespace crown