2019-09-23 21:04:01 -07:00
|
|
|
/*
|
|
|
|
* IXRedisServer.h
|
|
|
|
* Author: Benjamin Sergeant
|
|
|
|
* Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2020-06-10 22:30:55 -07:00
|
|
|
#include <ixwebsocket/IXSocket.h>
|
|
|
|
#include <ixwebsocket/IXSocketServer.h>
|
2019-09-23 21:04:01 -07:00
|
|
|
#include <functional>
|
2020-04-20 22:59:20 -07:00
|
|
|
#include <map>
|
2019-09-23 21:04:01 -07:00
|
|
|
#include <memory>
|
|
|
|
#include <mutex>
|
|
|
|
#include <set>
|
|
|
|
#include <string>
|
|
|
|
#include <thread>
|
|
|
|
#include <utility> // pair
|
|
|
|
|
|
|
|
namespace ix
|
|
|
|
{
|
|
|
|
class RedisServer final : public SocketServer
|
|
|
|
{
|
|
|
|
public:
|
|
|
|
RedisServer(int port = SocketServer::kDefaultPort,
|
|
|
|
const std::string& host = SocketServer::kDefaultHost,
|
|
|
|
int backlog = SocketServer::kDefaultTcpBacklog,
|
2020-01-26 16:17:26 -08:00
|
|
|
size_t maxConnections = SocketServer::kDefaultMaxConnections,
|
|
|
|
int addressFamily = SocketServer::kDefaultAddressFamily);
|
2019-09-23 21:04:01 -07:00
|
|
|
virtual ~RedisServer();
|
|
|
|
virtual void stop() final;
|
|
|
|
|
|
|
|
private:
|
|
|
|
// Member variables
|
|
|
|
std::atomic<int> _connectedClientsCount;
|
|
|
|
|
|
|
|
// Subscribers
|
|
|
|
// We could store connection states in there, to add better debugging
|
|
|
|
// since a connection state has a readable ID
|
2020-03-24 12:40:58 -07:00
|
|
|
std::map<std::string, std::set<Socket*>> _subscribers;
|
2019-09-23 21:04:01 -07:00
|
|
|
std::mutex _mutex;
|
|
|
|
|
|
|
|
std::atomic<bool> _stopHandlingConnections;
|
|
|
|
|
|
|
|
// Methods
|
2020-03-24 12:40:58 -07:00
|
|
|
virtual void handleConnection(std::unique_ptr<Socket>,
|
2020-07-08 12:10:35 -07:00
|
|
|
std::shared_ptr<ConnectionState> connectionState,
|
|
|
|
std::unique_ptr<ConnectionInfo> connectionInfo) final;
|
2019-09-23 21:04:01 -07:00
|
|
|
virtual size_t getConnectedClientsCount() final;
|
|
|
|
|
|
|
|
bool startsWith(const std::string& str, const std::string& start);
|
|
|
|
std::string writeString(const std::string& str);
|
|
|
|
|
2020-04-20 22:59:20 -07:00
|
|
|
bool parseRequest(std::unique_ptr<Socket>& socket, std::vector<std::string>& tokens);
|
2019-09-23 21:04:01 -07:00
|
|
|
|
2020-04-20 22:59:20 -07:00
|
|
|
bool handlePublish(std::unique_ptr<Socket>& socket, const std::vector<std::string>& tokens);
|
2019-09-23 21:04:01 -07:00
|
|
|
|
2020-03-24 12:40:58 -07:00
|
|
|
bool handleSubscribe(std::unique_ptr<Socket>& socket,
|
2019-09-23 21:04:01 -07:00
|
|
|
const std::vector<std::string>& tokens);
|
|
|
|
|
2020-04-20 22:59:20 -07:00
|
|
|
bool handleCommand(std::unique_ptr<Socket>& socket, const std::vector<std::string>& tokens);
|
2019-09-23 21:04:01 -07:00
|
|
|
|
2020-03-24 12:40:58 -07:00
|
|
|
void cleanupSubscribers(std::unique_ptr<Socket>& socket);
|
2019-09-23 21:04:01 -07:00
|
|
|
};
|
|
|
|
} // namespace ix
|