WebsocketClient - allows a user of this class to connect to a host url, and send and receive data asyncronously

This commit is contained in:
Taha Afzal committed 2021-10-04 15:55:46 -04:00
1 parent ce98e862c3
commit e34a2f5195
7 files changed
+748

No files matched your search

@@ -0,0 +1,19 @@
#pragma once
#include <cstddef>
namespace bts::spark::communication {
class WebsocketError;
class WebsocketMessage;
class IWebsocketListener {
public:
virtual void on_connection_established() = 0;
virtual void on_error(const WebsocketError &error) = 0;
virtual void on_write_complete(size_t message_id) = 0;
virtual void on_data(WebsocketMessage &msg) = 0;
virtual void on_timer() = 0;
virtual void on_connection_closed(bool gracefully) = 0;
};
} // namespace bts::spark::communication
@@ -0,0 +1,392 @@
#include "WebsocketClient.h"
#include "WebsocketClientConfiguration.h"
#include "WebsocketError.h"
#include "WebsocketMessage.h"
#include <atomic>
#include <bits/stdint-intn.h>
#include <bits/stdint-uintn.h>
#include <boost/asio.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/ts/netfwd.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/core/buffers_to_string.hpp>
#include <boost/beast/core/error.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/bind/bind.hpp>
#include <boost/bind/placeholders.hpp>
#include <boost/core/addressof.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
// #include <catch2/catch.hpp>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <ostream>
#include <queue>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <thread>
#include <tuple>
#include <utility>
#include <vector>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
namespace bts::spark::communication {
std::string get_thread_string() {
auto core_id = sched_getcpu();
std::thread::id thread_id = std::this_thread::get_id();
std::stringstream ss;
ss << "{thread_id:" << thread_id << " core:" << core_id << "}";
return ss.str();
}
// Sends a WebSocket message and prints the response
class WebsocketClientInternal
: public std::enable_shared_from_this<WebsocketClientInternal> {
private:
using WSCI = WebsocketClientInternal;
const WebsocketClientConfiguration _conf;
net::io_context &_io_context;
tcp::resolver _resolver;
websocket::stream<beast::tcp_stream> _ws;
beast::flat_buffer _read_buffer;
boost::asio::deadline_timer _timer;
IWebsocketListener *_listener;
// can't call async_read until the completion call
bool _pending_read = false;
// same for write
bool _pending_write = false;
// for send_message calls when there is_pending_write is true
std::queue<WebsocketMessage> _send_queue = {};
// this is just incremented and every read message is tagged with it
uint64_t _read_msg_id = 0;
// since there can only be one pending write at a time (ie we cant send an
// aysnc write until the last write's completion has been called)
uint64_t _pending_write_msg_id = 0;
// if any of the async call completion result in an error, this is set.
// this allows the timer
bool _encountered_error = false;
// oneway switch thats turned on once async_close is called
bool _close_attempted = false;
public:
// Resolver and socket require an io_context
explicit WebsocketClientInternal(
const WebsocketClientConfiguration &conf,
net::io_context &ioc,
IWebsocketListener *listener)
: _conf(conf), _io_context(ioc), _resolver(net::make_strand(ioc)),
_ws(net::make_strand(ioc)),
_timer(ioc, boost::posix_time::milliseconds(conf.timer_ms)),
_listener(listener) {}
// user facing function
void start() { _resolve(); }
void send_message(const WebsocketMessage &msg) {
_send_queue.push(msg);
_write_data();
}
void close_connection() {
if (!_close_attempted) {
_close_attempted = true;
_ws.async_close(
websocket::close_code::normal,
beast::bind_front_handler(&WSCI::_on_close, shared_from_this()));
}
}
private:
// Report a failure
static void _fail(beast::error_code ec, char const *what) {
std::cerr << what << ": " << ec.message() << std::endl;
}
void _handle_error(
beast::error_code error_code,
std::string &&err_msg,
WebsocketError::ErrorType err_type) {
_encountered_error = true;
std::stringstream str;
str << "Error_code:" << error_code << " Text:" << err_msg;
_listener->on_error({err_type, str.str()});
close_connection();
}
// Start the asynchronous operation
void _resolve() {
_resolver.async_resolve(
_conf.ip, _conf.port,
beast::bind_front_handler(&WSCI::_on_resolve, shared_from_this()));
}
void _on_resolve(
beast::error_code ec, const tcp::resolver::results_type &results) {
if (ec) {
_fail(ec, "resolve");
_handle_error(
ec, "Address resoloution failed",
WebsocketError::ErrorType::SETUP);
return;
}
// Set the timeout for the operation
beast::get_lowest_layer(_ws).expires_after(std::chrono::seconds(30));
// Make the connection on the IP address we get from a lookup
beast::get_lowest_layer(_ws).async_connect(
results,
beast::bind_front_handler(&WSCI::_on_connect, shared_from_this()));
}
void _on_connect(
beast::error_code ec,
const tcp::resolver::results_type::endpoint_type &ep) {
if (ec) {
_fail(ec, "connect");
_handle_error(
ec, "Connection failed", WebsocketError::ErrorType::SETUP);
return;
}
// Turn off the timeout on the tcp_stream, because
// the websocket stream has its own timeout system.
beast::get_lowest_layer(_ws).expires_never();
// Set suggested timeout settings for the websocket
_ws.set_option(
websocket::stream_base::timeout::suggested(beast::role_type::client));
// Set a decorator to change the User-Agent of the handshake
_ws.set_option(
websocket::stream_base::decorator([](websocket::request_type &req) {
req.set(
http::field::user_agent,
std::string(BOOST_BEAST_VERSION_STRING) +
" websocket-client-async");
}));
// Update the host_ string. This will provide the value of the
// Host HTTP header during the WebSocket handshake.
// See https://tools.ietf.org/html/rfc7230#section-5.4
auto host = _conf.ip + ':' + std::to_string(ep.port());
// spartan_assert(!host.empty());
// Perform the websocket handshake
_ws.async_handshake(
_conf.host_name, "/",
beast::bind_front_handler(&WSCI::_on_handshake, shared_from_this()));
}
void _on_handshake(beast::error_code ec) {
if (ec) {
_fail(ec, "handshake");
_handle_error(
ec, "Handshake failed", WebsocketError::ErrorType::SETUP);
return;
}
// this is when the connection is really established
_listener->on_connection_established();
_read_data();
_write_data();
_reinit_timer();
}
void _on_timer(beast::error_code ec) {
if (ec) {
_fail(ec, "timer");
_handle_error(ec, "Timer failed", WebsocketError::ErrorType::MISC);
return;
}
_listener->on_timer();
if (_is_active()) {
_reinit_timer();
}
}
void _reinit_timer() {
_timer.expires_at(
_timer.expires_at() +
boost::posix_time::milliseconds(_conf.timer_ms));
_timer.async_wait(
beast::bind_front_handler(&WSCI::_on_timer, shared_from_this()));
}
void _write_data() {
if (!_pending_write) {
if (!_send_queue.empty()) {
WebsocketMessage msg = _send_queue.front();
_pending_write_msg_id = msg.message_id;
_send_queue.pop();
_pending_write = true;
_ws.async_write(
net::buffer(msg.data, msg.data_size),
beast::bind_front_handler(
&WSCI::_on_write, shared_from_this()));
}
}
}
void _read_data() {
if (!_pending_read) {
_pending_read = true;
_ws.async_read(
_read_buffer,
beast::bind_front_handler(&WSCI::_on_read, shared_from_this()));
}
}
void _on_write(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
_fail(ec, "write");
_handle_error(
ec, "Write failed", WebsocketError::ErrorType::WRITE_FAILED);
return;
}
_pending_write = false;
// Read a message into our buffer
_listener->on_write_complete(_pending_write_msg_id);
_read_data();
_write_data();
}
void _on_read(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
_fail(ec, "read");
_handle_error(
ec, "Read failed", WebsocketError::ErrorType::READ_FAILED);
return;
}
_pending_read = false;
WebsocketMessage msg = {
_read_msg_id++,
static_cast<char const *>(_read_buffer.cdata().data()),
_read_buffer.data().size()};
_listener->on_data(msg);
_read_buffer.clear();
_read_data();
_write_data();
}
void _on_close(beast::error_code ec) {
if (ec) {
_fail(ec, "close");
_listener->on_connection_closed(false);
return;
}
_listener->on_connection_closed(true);
// If we get here then the connection is closed gracefully
// The make_printable() function helps print a ConstBufferSequence
std::cout << "on_close"
<< " last data:" << beast::make_printable(_read_buffer.data())
<< std::endl;
}
bool _is_active() const { return !_encountered_error && !_close_attempted; }
};
extern "C" {
struct WebsocketMessageWrapper {
std::uint64_t message_id;
std::unique_ptr<char[]> data; // NOLINT
size_t data_size;
explicit WebsocketMessageWrapper(const WebsocketMessage &msg)
: message_id(msg.message_id),
data(std::make_unique<char[]>(msg.data_size)), // NOLINT
data_size(msg.data_size) {
memcpy(data.get(), msg.data, msg.data_size);
}
[[nodiscard]] WebsocketMessage get_msg() const {
return {message_id, data.get(), data_size};
}
bool operator<(const WebsocketMessageWrapper &m) const {
return message_id < m.message_id;
}
};
}
struct WebsocketClient::PImpl {
const WebsocketClientConfiguration conf;
IWebsocketListener *listener;
// this is used outside of the start loop
WebsocketClientInternal *wsci = nullptr;
std::vector<WebsocketMessageWrapper> cached_messages = {};
bool ioc_blocked = false;
explicit PImpl(
WebsocketClientConfiguration conf_a, IWebsocketListener *listener_a)
: conf(std::move(conf_a)), listener(listener_a) {}
};
WebsocketClient::WebsocketClient(
const WebsocketClientConfiguration &conf, IWebsocketListener *listener) {
me = std::make_unique<PImpl>(conf, listener);
// me = new PImpl(conf, listener);
}
// this is a blocking call
void WebsocketClient::start() {
for (size_t i = 0; i < me->conf.n_reconnection_attempts; i++) {
net::io_context ioc;
std::shared_ptr<WebsocketClientInternal> wsci =
std::make_shared<WebsocketClientInternal>(me->conf, ioc, this);
me->wsci = wsci.get();
// this also puts something in the io_context "work queue" to stop
// it from ending auto ip_cstr = _ip.c_str();
me->ioc_blocked = true;
wsci->start();
ioc.run();
me->ioc_blocked = false;
me->cached_messages.clear();
std::this_thread::sleep_for(
std::chrono::milliseconds(me->conf.msecs_bw_connection_tries));
}
}
void WebsocketClient::send_message(const WebsocketMessage &msg) {
const auto &msg_copy = me->cached_messages.emplace_back(msg);
me->wsci->send_message(msg_copy.get_msg());
}
void close_connection() {}
// interface methods
void WebsocketClient::on_connection_established() {
// spartan_assert(me->ioc_blocked);
me->listener->on_connection_established();
}
void WebsocketClient::on_error(const WebsocketError &error) {
// spartan_assert(me->ioc_blocked);
me->listener->on_error(error);
}
void WebsocketClient::on_write_complete(size_t message_id) {
// _assert(me->ioc_blocked);
me->cached_messages.erase(
std::remove_if(
me->cached_messages.begin(), me->cached_messages.end(),
[&](const auto &m) { return m.message_id == message_id; }),
me->cached_messages.end());
me->listener->on_write_complete(message_id);
}
void WebsocketClient::on_data(WebsocketMessage &msg) {
// spartan_assert(me->ioc_blocked);
me->listener->on_data(msg);
}
void WebsocketClient::on_timer() { me->listener->on_timer(); }
void WebsocketClient::on_connection_closed(bool gracefully) {
me->listener->on_connection_closed(gracefully);
}
WebsocketClient::~WebsocketClient() = default;
} // namespace bts::spark::communication
@@ -0,0 +1,35 @@
#pragma once
#include "IWebsocketListener.h"
#include <memory>
#include <string>
namespace bts::spark::communication {
struct WebsocketClientConfiguration;
class WebsocketClient : public IWebsocketListener,
public std::enable_shared_from_this<WebsocketClient> {
private:
struct PImpl;
std::unique_ptr<PImpl> me;
public:
WebsocketClient(
const WebsocketClientConfiguration &conf, IWebsocketListener *listener);
// ~WebsocketClient() = default;
// this is a blocking call
void start();
void send_message(const WebsocketMessage &msg);
// interface methods
void on_connection_established() override;
void on_error(const WebsocketError &error) override;
void on_write_complete(size_t message_id) override;
void on_data(WebsocketMessage &msg) override;
void on_timer() override;
void on_connection_closed(bool gracefully) override;
~WebsocketClient();
};
} // namespace bts::spark::communication
@@ -0,0 +1,17 @@
#pragma once
#include <string>
namespace bts::spark::communication {
struct WebsocketClientConfiguration {
const std::string ip;
const std::string port;
// this can not be derived form the ip and port only
const std::string host_name;
const size_t n_reconnection_attempts;
const size_t msecs_bw_connection_tries;
const size_t timer_ms;
};
} // namespace bts::spark::communication
@@ -0,0 +1,19 @@
#pragma once
#include <string>
namespace bts::spark::communication {
struct WebsocketError {
enum class ErrorType {
SETUP = 0,
DISCONNECT,
WRITE_FAILED,
READ_FAILED,
MISC
};
ErrorType error_type;
std::string message;
};
} // namespace bts::spark::communication
@@ -0,0 +1,20 @@
#pragma once
#include <string>
#include <vector>
namespace bts::spark::communication {
struct WebsocketMessage {
// user controls the message_id. callback for write complete is called
// using this id
const std::uint64_t message_id;
char const *data;
const size_t data_size;
[[nodiscard]] std::vector<char> convert_to_vector() const {
std::vector<char> rv(data, data + data_size); // NOLINT
return rv;
}
};
} // namespace bts::spark::communication
@@ -0,0 +1,246 @@
#include "lib/communincation/websockets/IWebsocketListener.h"
#include "lib/communincation/websockets/WebsocketClient.h"
#include "lib/communincation/websockets/WebsocketClientConfiguration.h"
#include "lib/communincation/websockets/WebsocketError.h"
#include "lib/communincation/websockets/WebsocketMessage.h"
#include <atomic>
#include <bits/stdint-intn.h>
#include <bits/stdint-uintn.h>
#include <boost/asio.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/ts/netfwd.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/core/buffers_to_string.hpp>
#include <boost/beast/core/error.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/bind/bind.hpp>
#include <boost/bind/placeholders.hpp>
#include <boost/core/addressof.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <catch/catch.hpp>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <ostream>
#include <queue>
#include <random>
#include <sstream>
#include <stdio.h>
#include <string>
#include <sys/types.h>
#include <thread>
#include <tuple>
#include <utility>
#include <vector>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
// using namespace
namespace bts::spark::communication {
class RandomGenerator {
public:
double random_double(double min, double max) {
// Standard mersenne_twister_engine seeded with rd()
std::mt19937 gen(rd());
return std::uniform_real_distribution<>(min, max)(gen);
}
int random_int(int min, int max) {
return static_cast<int>(random_double(min, max));
}
private:
std::random_device rd;
};
std::string get_random_string(size_t min_l, size_t max_l) {
RandomGenerator rg = {};
int len = rg.random_int(static_cast<int>(min_l), static_cast<int>(max_l));
std::string rv = {};
for (auto i = 0; i < len; i++) {
// 65-90
int ic = rg.random_int(65, 90);
char c = static_cast<char>(ic);
rv.append(&c, 1);
}
return rv;
}
class SyncWebsocketEchoServer {
public:
const std::string ip;
const std::string port;
SyncWebsocketEchoServer(std::string ip_a, std::string port_a)
: ip(std::move(ip_a)), port(std::move(port_a)) {}
static std::string get_thread_string() {
auto core_id = sched_getcpu();
std::thread::id thread_id = std::this_thread::get_id();
std::stringstream ss;
ss << "{thread_id:" << thread_id << " core:" << core_id << "}";
return ss.str();
}
static void print_thread() {
auto core_id = sched_getcpu();
std::thread::id thread_id = std::this_thread::get_id();
std::cout << "Thread details id:" << thread_id << " core:" << core_id
<< std::endl;
}
static void handle_single_session(tcp::socket socket) {
try {
auto remote_ep = socket.remote_endpoint();
std::cout << "New connection local_endpoint:"
<< socket.local_endpoint()
<< " remote_endpoint:" << socket.remote_endpoint()
<< std::endl;
print_thread();
websocket::stream<tcp::socket> ws{std::move(socket)};
// Set a decorator to change the Server of the handshake
ws.set_option(websocket::stream_base::decorator(
[](websocket::response_type &res) {
res.set(
http::field::server,
std::string(BOOST_BEAST_VERSION_STRING) +
" websocket-server-sync");
}));
// Accept the websocket handshake
ws.accept();
auto n_msgs = 0;
for (;;) {
// This buffer will hold the incoming message
beast::flat_buffer buffer;
// Read a message
ws.read(buffer);
ws.text(ws.got_text());
std::string recv_txt = beast::buffers_to_string(buffer.data());
n_msgs++;
// std::cout << "Received data:" << recv_txt << " from:" <<
// remote_ep
// << std::endl;
std::cout << "Received msg#: " << n_msgs
<< " sz:" << recv_txt.size() << " from:" << remote_ep
<< std::endl;
// invert the text and echo it
auto send_i_txt = recv_txt;
std::cout << "Sending data:(after sleeping) sz: "
<< send_i_txt.size() << " to:" << remote_ep << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
ws.write(net::buffer(send_i_txt));
}
} catch (beast::system_error const &se) {
// This indicates that the session was closed
if (se.code() != websocket::error::closed) {
std::cerr << "Error: " << se.code().message() << std::endl;
}
} catch (std::exception const &e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
void accept_connection() {
try {
auto const address_ip = boost::asio::ip::make_address(ip);
auto const address_port = static_cast<unsigned short>(std::stoi(port));
// The io_context is required for all I/O
net::io_context ioc{1};
std::cout << "Starting websocket server on ip:" << ip
<< " port:" << port << std::endl;
// The acceptor receives incoming connections
tcp::acceptor acceptor{ioc, {address_ip, address_port}};
for (;;) {
// This will receive the new connection
tcp::socket socket{ioc};
// Block until we get a connection
acceptor.accept(socket);
std::cout << "Connection accepted" << std::endl;
// Launch the session, transferring ownership of the socket
// copy cons is deleted for socket
auto conn_wrapper = [&](tcp::socket s) {
handle_single_session(std::move(s));
};
std::thread socket_thread(conn_wrapper, std::move(socket));
socket_thread.detach();
}
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
return;
}
}
};
TEST_CASE("WebsocketEchoServer", "[websocketserver]") {
SyncWebsocketEchoServer serv("127.0.0.1", "8083");
serv.accept_connection();
}
TEST_CASE("WebsocketClientTest", "[websocketclient]") {
class WebsocketSync : public IWebsocketListener {
public:
std::shared_ptr<WebsocketClient> wsc = nullptr;
const int msg_burst_sz = 20;
uint64_t msg_id = 0;
int n_msgs_recv = 0;
int n_msgs_send = 0;
WebsocketSync() = default;
void on_connection_established() override {
std::cout << "*** Listener::connection established" << std::endl;
n_msgs_recv = 0;
n_msgs_send = 0;
}
void on_error(const WebsocketError &error) override {
std::cout << "*** Listener:on_error " << error.message << std::endl;
}
void on_write_complete(size_t message_id) override {
std::cout << "*** Listener::on_write_complete message_id: "
<< message_id << std::endl;
}
void on_data(WebsocketMessage &msg) override {
n_msgs_recv++;
std::cout << "*** Listener::on_data sz: " << msg.data_size
<< " n_msgs_recv: " << n_msgs_recv << std::endl;
}
void on_timer() override {
std::cout << "*** Listener::on_timer" << std::endl;
if (n_msgs_send == n_msgs_recv) {
send_msg(msg_burst_sz);
}
}
void on_connection_closed(bool gracefully) override {
std::cout << "*** Listener::on_connection_closed gracefully: "
<< gracefully << std::endl;
}
void send_msg(int n_msgs = 1) {
for (auto i = 0; i < n_msgs; i++) {
auto text = get_random_string(5, 20);
WebsocketMessage msg{msg_id++, text.c_str(), text.size()};
wsc->send_message(msg);
n_msgs_send++;
std::cout << "*** Listener::send_message sz: " << text.size()
<< " n_msgs_send: " << n_msgs_send << std::endl;
}
}
};
WebsocketSync l;
std::shared_ptr<WebsocketClient> c = std::make_shared<WebsocketClient>(
WebsocketClientConfiguration{
"127.0.0.1", "8083", "127.0.0.1:8083", 10, 10000, 1000},
&l);
l.wsc = c;
// blocking call
c->start();
std::cout << "Test end" << std::endl;
}
} // namespace bts::spark::communication