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>
|
2018-12-31 06:16:05 +01:00
|
|
|
#include <thread>
|
2019-01-01 22:47:25 +01:00
|
|
|
#include <mutex>
|
2018-12-31 07:12:13 +01:00
|
|
|
#include <functional>
|
2019-01-01 22:53:13 +01:00
|
|
|
#include <memory>
|
2018-12-31 07:12:13 +01:00
|
|
|
|
|
|
|
#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-31 07:12:13 +01:00
|
|
|
|
2018-12-30 08:15:27 +01:00
|
|
|
class WebSocketServer {
|
|
|
|
public:
|
2019-01-01 23:28:41 +01:00
|
|
|
WebSocketServer(int port = 8080,
|
|
|
|
const std::string& host = WebSocketServer::kDefaultHost,
|
|
|
|
int backlog = 5);
|
2018-12-30 08:15:27 +01:00
|
|
|
virtual ~WebSocketServer();
|
|
|
|
|
2018-12-31 07:12:13 +01:00
|
|
|
void setOnConnectionCallback(const OnConnectionCallback& callback);
|
2019-01-01 23:52:14 +01:00
|
|
|
void start();
|
2018-12-31 07:12:13 +01:00
|
|
|
|
2018-12-31 07:00:49 +01:00
|
|
|
std::pair<bool, std::string> listen();
|
2018-12-30 08:15:27 +01:00
|
|
|
|
2019-01-01 23:28:41 +01:00
|
|
|
// Get all the connected clients
|
|
|
|
std::set<std::shared_ptr<WebSocket>> getClients();
|
2019-01-01 22:47:25 +01:00
|
|
|
|
2018-12-31 07:00:49 +01:00
|
|
|
private:
|
2019-01-01 23:28:41 +01:00
|
|
|
// Member variables
|
2018-12-30 08:15:27 +01:00
|
|
|
int _port;
|
2019-01-01 23:28:41 +01:00
|
|
|
std::string _host;
|
2018-12-31 07:00:49 +01:00
|
|
|
int _backlog;
|
|
|
|
|
2018-12-31 07:12:13 +01:00
|
|
|
OnConnectionCallback _onConnectionCallback;
|
|
|
|
|
2018-12-31 07:00:49 +01:00
|
|
|
// socket for accepting connections
|
|
|
|
int _serverFd;
|
2018-12-31 06:16:05 +01:00
|
|
|
|
2019-01-01 23:28:41 +01:00
|
|
|
std::mutex _clientsMutex;
|
2019-01-01 22:53:13 +01:00
|
|
|
std::set<std::shared_ptr<WebSocket>> _clients;
|
2019-01-01 23:28:41 +01:00
|
|
|
|
|
|
|
std::mutex _logMutex;
|
|
|
|
|
2019-01-01 23:52:14 +01:00
|
|
|
std::atomic<bool> _stop;
|
|
|
|
std::thread _thread;
|
|
|
|
|
2019-01-01 23:28:41 +01:00
|
|
|
const static std::string kDefaultHost;
|
|
|
|
|
|
|
|
// Methods
|
2019-01-01 23:52:14 +01:00
|
|
|
void run();
|
|
|
|
void stop();
|
2019-01-01 23:28:41 +01:00
|
|
|
void handleConnection(int fd);
|
|
|
|
|
|
|
|
// Logging
|
|
|
|
void logError(const std::string& str);
|
|
|
|
void logInfo(const std::string& str);
|
2018-12-30 08:15:27 +01:00
|
|
|
};
|
|
|
|
}
|