ASIO Client Server Framework
Loading...
Searching...
No Matches
client.h
1#pragma once
2#include <utility>
3#include <boost/asio.hpp>
4#include <iostream>
5#include <thread>
6
7#include "message_queue.h"
8#include "connection.h"
9
10#include "timeout_manager.h"
11#include "logger.h"
12
13namespace acsf
14{
30 class Client {
31 private:
32 // Boost
33 boost::asio::io_context io_context_;
34 boost::asio::ip::tcp::socket clientSocket_;
35 boost::asio::ip::tcp::endpoint endpoint_;
36 boost::asio::executor_work_guard<boost::asio::io_context::executor_type> workGuard_;
37 Logger logger_;
38
39 std::thread workerThread_;
40 MessageQueue messageQueue_;
41 std::shared_ptr<Connection> clientCon_;
42 std::atomic_bool isClosed_ = false;
43 std::function<void()> callBack_;
44 TimeoutManager timeoutManager_;
45 bool keepAliveByHeartBeat;
46 bool sendHeartBeat;
47
48
49 void log(LogLevel level, std::string message, const boost::system::error_code& ec = {}){
50 Log log;
51 log.level = level;
52 log.message = std::move(message);
53 log.remoteAddress = endpoint_.address().to_string();
54 log.remotePort = endpoint_.port();
55 if(ec){
56 log.errorValue = ec.value();
57 log.errorMessage = ec.message();
58 }
59 logger_.push(std::move(log));
60 }
61
62 void handleConnection(boost::asio::ip::tcp::socket socket, std::function<void()> callback){
63 clientCon_ = std::make_shared<Connection>(std::move(socket), 0, messageQueue_, timeoutManager_, logger_, callback, keepAliveByHeartBeat, sendHeartBeat);
64 clientCon_->start();
65 }
66
67 public:
68
78 Client(std::string ip, std::uint16_t port, std::function<void()> callBack = [](){}, bool keepAliveByHeartBeat = false, bool sendHeartBeats = true, LoggerConfig loggerConfig = {}):
79 clientSocket_(io_context_),
80 endpoint_(boost::asio::ip::make_address(ip), port),
81 workGuard_(boost::asio::make_work_guard(io_context_)),
82 logger_(io_context_, std::move(loggerConfig)),
83 callBack_(callBack),
84 keepAliveByHeartBeat(keepAliveByHeartBeat),
85 sendHeartBeat(sendHeartBeats)
86 {}
87
90 stop();
91 }
92
98 boost::system::error_code start(){
99 if(clientCon_) {
100 log(LogLevel::WARN, "start() called while already connected", boost::asio::error::already_connected);
101 return boost::asio::error::already_connected;
102 }
103 boost::system::error_code ec;
104 clientSocket_.connect(endpoint_, ec);
105 if(ec) {
106 log(LogLevel::ERROR, "Failed to connect to server", ec);
107 return ec;
108 }
109 handleConnection(std::move(clientSocket_), [this]{
110 messageQueue_.close();
111 if (callBack_) callBack_();
112 }); // Also close msg queue with callback to free waiting recv calls
113
114 workerThread_ = std::thread([this]() {
115 io_context_.run();
116 });
117
118 return boost::system::error_code();
119
120 }
121
126 void stop(){
127 if(isClosed_.exchange(true)) {return;}
128
129 workGuard_.reset();
130 messageQueue_.close();
131
132 if(clientCon_) { clientCon_->close(); } // Call back called from connection class
133
134 if (workerThread_.joinable()) {
135 workerThread_.join();
136 }
137 io_context_.stop();
138 logger_.unsafeFlushNow();
139 }
140
145 std::optional<acsf::Message> receive(){
146 return messageQueue_.pop();
147 }
148
154 void send(std::string body){
155 if(!clientCon_) { return; }
156 clientCon_->send(std::move(body));
157 }
158
159
160 };
161}
std::optional< acsf::Message > receive()
Blocks until a message arrives from the server.
Definition client.h:145
~Client()
Stops the client (see stop()) and releases its resources.
Definition client.h:89
boost::system::error_code start()
Connects to the server and starts the I/O thread.
Definition client.h:98
void send(std::string body)
Queues a message to be sent to the server.
Definition client.h:154
void stop()
Closes the connection, wakes any thread blocked in receive() and joins the I/O thread....
Definition client.h:126
Client(std::string ip, std::uint16_t port, std::function< void()> callBack=[](){}, bool keepAliveByHeartBeat=false, bool sendHeartBeats=true, LoggerConfig loggerConfig={})
Creates a client. Nothing is connected until start() is called.
Definition client.h:78
Writes log entries to rotating files in the background. Used internally by Server and Client.
Definition logger.h:131
Everything in the framework lives in this namespace.
LogLevel
Severity of a log entry.
Definition logger.h:19
@ WARN
Definition logger.h:25
@ ERROR
Definition logger.h:27
One log entry. Every field is optional and only the fields that are set appear in the output.
Definition logger.h:46
std::optional< LogLevel > level
Definition logger.h:51
Logging settings passed to acsf::Server and acsf::Client.
Definition logger.h:118