Header Only Library
TCP Client
How to use TCP client class
References
#include "ip.hpp"
#include "ip/tcp/tcpclient.hpp"
Syntax
namespace internetprotocol
class tcp_client_c
#include "ip.hpp"
using namespace internetprotocol;
int main(int argc, char** argv) {
tcp_client_c net;
net.on_error = [&](const asio::error_code &ec) {
std::cout << ec.message() << std::endl;
};
net.on_message_received = [&](const std::vector<uint8_t> &buffer, const size_t bytes_recv) {
std::cout << buffer_to_string(buffer) << std::endl;
};
net.connect();
std::string input;
while (std::getline(std::cin, input)) {
if (input == "quit") {
net.close();
break;
}
net.write(input, [](const asio::error_code &ec, size_t bytes_sent) {
// Check if message has been sent
});
}
join_threads();
return 0;
}
Functions
Is Open
- Return true if socket is open.
bool is_open() const
Local Endpoint
- Get the local endpoint of the socket. Use this function only after open connection.
tcp::endpoint local_endpoint() const
Remote Endpoint
- Get the remote endpoint of the socket. Use this function only after open connection.
tcp::endpoint remote_endpoint() const
Get Error Code
- Return a const ref of the latest error code returned by asio.
const asio::error_code &get_error_code() const
Write
- Send a string message
- Return false if message is empty or socket is closed
- Warning: If you’re using Windows, ensure that you are sending characters compatible with UTF*8
bool write(const std::string &message, const std::function<void(const asio::error_code &, const size_t)> &callback = nullptr)
Write Buffer
- Send a buffer message
- Return false if message is empty or socket is closed
bool write_buffer(const std::vector<uint8_t> &buffer, const std::function<void(const asio::error_code &, const size_t)> &callback = nullptr)
Connect
- Connect to the host
- Return true if It's able to connect
bool connect(const client_bind_options_t &bind_opts = {})
Close
- Close connection
void close()
Events
On Connected
- Event triggered when a connection is estabilished
std::function<void()> on_connected
On Message Received
- Event triggered when a message is received
- Use
buffer_to_string()
function to convertestd::vector<uint8_t>
tostd::string
std::function<void(const std::vector<uint8_t> &, const size_t)> on_message_received
On Close
- Event triggered when socket is closed
std::function<void()> on_close
On Error
- Event triggered if any error occur during async process
const asio::error_code &
: if error occur, error code will be different from 0- Normally, when an error occurs, the socket is automatically closed, triggering the
on_close
event.
std::function<void(const asio::error_code &)> on_error