Files
crossdesk/src/ws/ws_core.h

73 lines
1.8 KiB
C++

#ifndef _WS_CORE_H_
#define _WS_CORE_H_
#include <condition_variable>
#include <map>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include "websocketpp/client.hpp"
#include "websocketpp/common/memory.hpp"
#include "websocketpp/common/thread.hpp"
#include "websocketpp/config/asio_no_tls_client.hpp"
typedef websocketpp::client<websocketpp::config::asio_client> client;
enum WsStatus { WsOpening = 0, WsOpened, WsFailed, WsClosed, WsReconnecting };
class WsCore {
public:
WsCore();
virtual ~WsCore();
int Connect(std::string const &uri);
void Close(websocketpp::close::status::value code =
websocketpp::close::status::going_away,
std::string reason = "");
void Send(std::string message);
void Ping(websocketpp::connection_hdl hdl);
WsStatus GetStatus();
// Callback
void OnOpen(client *c, websocketpp::connection_hdl hdl);
void OnFail(client *c, websocketpp::connection_hdl hdl);
void OnClose(client *c, websocketpp::connection_hdl hdl);
bool OnPing(websocketpp::connection_hdl hdl, std::string msg);
bool OnPong(websocketpp::connection_hdl hdl, std::string msg);
void OnPongTimeout(websocketpp::connection_hdl hdl, std::string msg);
void OnMessage(websocketpp::connection_hdl hdl, client::message_ptr msg);
virtual void OnReceiveMessage(const std::string &msg) = 0;
virtual void OnWsStatus(WsStatus ws_status) = 0;
private:
client m_endpoint_;
websocketpp::connection_hdl connection_handle_;
std::thread m_thread_;
std::thread ping_thread_;
bool running_ = true;
std::mutex mtx_;
unsigned int interval_ = 3;
std::condition_variable cond_var_;
WsStatus ws_status_ = WsStatus::WsClosed;
int timeout_count_ = 0;
std::string uri_;
bool destructed_ = false;
};
#endif