IXWebSocket/ixwebsocket/IXWebSocketServer.h

83 lines
2.2 KiB
C
Raw Normal View History

2018-12-30 08:15:27 +01:00
/*
* IXWebSocketServer.h
* Author: Benjamin Sergeant
* Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
*/
#pragma once
#include <utility> // pair
#include <string>
2019-01-01 22:47:25 +01:00
#include <set>
#include <thread>
2019-01-01 22:47:25 +01:00
#include <mutex>
#include <functional>
2019-01-01 22:53:13 +01:00
#include <memory>
#include <condition_variable>
#include "IXWebSocket.h"
2018-12-30 08:15:27 +01:00
namespace ix
{
2019-01-01 22:53:13 +01:00
using OnConnectionCallback = std::function<void(std::shared_ptr<WebSocket>)>;
2018-12-30 08:15:27 +01:00
class WebSocketServer {
public:
2019-01-02 04:23:27 +01:00
WebSocketServer(int port = WebSocketServer::kDefaultPort,
const std::string& host = WebSocketServer::kDefaultHost,
int backlog = WebSocketServer::kDefaultTcpBacklog,
2019-01-04 03:33:08 +01:00
size_t maxConnections = WebSocketServer::kDefaultMaxConnections,
int handshakeTimeoutSecs = WebSocketServer::kDefaultHandShakeTimeoutSecs);
2018-12-30 08:15:27 +01:00
virtual ~WebSocketServer();
void setOnConnectionCallback(const OnConnectionCallback& callback);
void start();
void wait();
void stop();
std::pair<bool, std::string> listen();
2018-12-30 08:15:27 +01:00
// Get all the connected clients
std::set<std::shared_ptr<WebSocket>> getClients();
2019-01-01 22:47:25 +01:00
private:
// Member variables
2018-12-30 08:15:27 +01:00
int _port;
std::string _host;
int _backlog;
size_t _maxConnections;
2019-01-04 03:33:08 +01:00
int _handshakeTimeoutSecs;
OnConnectionCallback _onConnectionCallback;
// socket for accepting connections
int _serverFd;
std::mutex _clientsMutex;
2019-01-01 22:53:13 +01:00
std::set<std::shared_ptr<WebSocket>> _clients;
std::mutex _logMutex;
std::atomic<bool> _stop;
std::thread _thread;
std::condition_variable _conditionVariable;
std::mutex _conditionVariableMutex;
2019-01-02 04:23:27 +01:00
const static int kDefaultPort;
const static std::string kDefaultHost;
2019-01-02 04:23:27 +01:00
const static int kDefaultTcpBacklog;
const static size_t kDefaultMaxConnections;
2019-01-04 03:33:08 +01:00
const static int kDefaultHandShakeTimeoutSecs;
// Methods
void run();
void handleConnection(int fd);
size_t getConnectedClientsCount();
// Logging
void logError(const std::string& str);
void logInfo(const std::string& str);
2018-12-30 08:15:27 +01:00
};
}