Add websocket session tracking

This commit is contained in:
Eric Harding committed 2018-04-11 18:11:50 -04:00
1 parent f50118fb45
commit 4d3a0375aa
1 file changed
+32 -12
+32 -12
View File
@@ -2,6 +2,7 @@
#include "lib/utils/Dispatcher.h"
#include "lib/api/core/ApiClientInterop.h"
#include "lib/logging/logging.h"
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
@@ -21,7 +22,6 @@ typedef std::string ApiKey;
typedef websocketpp::server<websocketpp::config::asio> WsServer;
using websocketpp::connection_hdl;
// using websocketpp::server;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
@@ -37,16 +37,18 @@ std::string read_file(const std::string& path) {
namespace bts {
namespace http {
struct Client {
struct Session {
std::mutex m;
std::unordered_map<std::string, api::ApiClient*> apiclient;
std::vector<api::TableSubscription> subscriptions;
Client():
m(), apiclient(), subscriptions()
char count;
Session():
m(), apiclient(), subscriptions(), count('a')
{}
~Client() {
~Session() {
std::lock_guard<std::mutex> lock(m);
// unsubscribe
// delete clients
@@ -56,7 +58,7 @@ namespace http {
struct ServerState {
std::mutex _m;
utils::Dispatcher& _dispatcher;
std::map<connection_hdl, Client> _clients;
std::map<connection_hdl, std::unique_ptr<Session>, std::owner_less<connection_hdl>> _session;
WsServer _server;
int _port;
std::string _root;
@@ -65,7 +67,7 @@ namespace http {
ServerState(const api::ServiceContext ctx, int port, const char* web_root) :
_m(),
_dispatcher(utils::Dispatcher::get_named("Webserver")),
_clients(),
_session(),
_server(),
_port(port),
_root(web_root),
@@ -82,21 +84,40 @@ namespace http {
run();
}
// starts listening
void run() {
_server.listen(_port);
_server.start_accept();
}
void on_open(connection_hdl hdl) {
(void)hdl;
auto con = _server.get_con_from_hdl(hdl);
if (con) {
LOG(Api,Info, "Web client connection from {}", con->get_remote_endpoint());
std::lock_guard<std::mutex> lock(_m);
_session[hdl] = std::make_unique<Session>();
}
}
void on_close(connection_hdl hdl) {
(void)hdl;
auto con = _server.get_con_from_hdl(hdl);
if (con) {
LOG(Api,Info, "Web client disconnected: {}", con->get_remote_endpoint());
std::lock_guard<std::mutex> lock(_m);
_session.erase(hdl);
}
}
void on_message(connection_hdl hdl, WsServer::message_ptr msg) {
(void)hdl;
(void)msg;
std::lock_guard<std::mutex> lock(_m);
auto iter = _session.find(hdl);
if (iter != _session.end()) {
LOG(Api,Info, "Got: {}", msg->get_payload());
_server.send(hdl, "Your message has been received: " , websocketpp::frame::opcode::text);
}
}
void on_http(connection_hdl hdl) {
auto con = _server.get_con_from_hdl(hdl);
auto resource = con->get_resource();
@@ -163,7 +184,6 @@ namespace http {
}
else if (boost::filesystem::is_regular_file(path)) {
con->set_body(read_file(path.string()));
con->set_status(websocketpp::http::status_code::ok);
}
else {