You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.5 KiB

4 months ago
  1. /*
  2. * IXWebSocketServer.h
  3. * Author: Benjamin Sergeant
  4. * Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
  5. */
  6. #pragma once
  7. #include "IXSocketServer.h"
  8. #include "IXWebSocket.h"
  9. #include <condition_variable>
  10. #include <functional>
  11. #include <memory>
  12. #include <mutex>
  13. #include <set>
  14. #include <string>
  15. #include <thread>
  16. #include <utility> // pair
  17. namespace ix
  18. {
  19. class WebSocketServer : public SocketServer
  20. {
  21. public:
  22. using OnConnectionCallback =
  23. std::function<void(std::weak_ptr<WebSocket>, std::shared_ptr<ConnectionState>)>;
  24. using OnClientMessageCallback = std::function<void(
  25. std::shared_ptr<ConnectionState>, WebSocket&, const WebSocketMessagePtr&)>;
  26. WebSocketServer(int port = SocketServer::kDefaultPort,
  27. const std::string& host = SocketServer::kDefaultHost,
  28. int backlog = SocketServer::kDefaultTcpBacklog,
  29. size_t maxConnections = SocketServer::kDefaultMaxConnections,
  30. int handshakeTimeoutSecs = WebSocketServer::kDefaultHandShakeTimeoutSecs,
  31. int addressFamily = SocketServer::kDefaultAddressFamily);
  32. virtual ~WebSocketServer();
  33. virtual void stop() final;
  34. void enablePong();
  35. void disablePong();
  36. void disablePerMessageDeflate();
  37. void setOnConnectionCallback(const OnConnectionCallback& callback);
  38. void setOnClientMessageCallback(const OnClientMessageCallback& callback);
  39. // Get all the connected clients
  40. std::set<std::shared_ptr<WebSocket>> getClients();
  41. void makeBroadcastServer();
  42. bool listenAndStart();
  43. const static int kDefaultHandShakeTimeoutSecs;
  44. int getHandshakeTimeoutSecs();
  45. bool isPongEnabled();
  46. bool isPerMessageDeflateEnabled();
  47. private:
  48. // Member variables
  49. int _handshakeTimeoutSecs;
  50. bool _enablePong;
  51. bool _enablePerMessageDeflate;
  52. OnConnectionCallback _onConnectionCallback;
  53. OnClientMessageCallback _onClientMessageCallback;
  54. std::mutex _clientsMutex;
  55. std::set<std::shared_ptr<WebSocket>> _clients;
  56. const static bool kDefaultEnablePong;
  57. // Methods
  58. virtual void handleConnection(std::unique_ptr<Socket> socket,
  59. std::shared_ptr<ConnectionState> connectionState);
  60. virtual size_t getConnectedClientsCount() final;
  61. };
  62. } // namespace ix