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