Internet Protocol
Header Only Library

TCP Client Openssl

How to use TCP client class with openssl

References

#include "ip.hpp"
#include "ip/tcp/tcpclient.hpp"
#define ENABLE_SSL

Syntax

namespace internetprotocol
class tcp_client_ssl_c
#include <iostream>
#define ENABLE_SSL
#include <ip/tcp/tcpclient.hpp>

using namespace internetprotocol;

std::string loadfile(const std::string& file) {
    std::ifstream arquivo(file);

    if (!arquivo.is_open()) {
        throw std::runtime_error("Erro trying to open file: " + file);
    }

    std::stringstream buffer;
    buffer << arquivo.rdbuf();

    return buffer.str();
}
// Relative path to the files
const std::string cert = loadfile("cert.pem");
const std::string key = loadfile("key.pem");
const std::string csr = loadfile("csr.pem");
const std::string ca_cert = loadfile("ca-cert.pem");

int main()
{
    tcp_client_ssl_c net({ key, cert, "", "", file_format_e::pem, none, "" });
    net.on_error = [&](const asio::error_code &ec) {
        std::cout << ec.message() << std::endl;
    };
    net.on_client_accepted = [&](const std::shared_ptr<tcp_remote_c> &client) {
        client->on_message_received = [&, client](const std::vector<uint8_t> &buffer, const size_t bytes_recvd) {
            std::cout << client->local_endpoint().port() << " -> " << buffer_to_string(buffer) << std::endl;
        };
        client->on_close = [&, client]() {
            std::cout << "client logout" << std::endl;
        };
    };
    net.open();

    std::string input;
    while (std::getline(std::cin, input)) {
        if (input == "quit") {
            net.close();
            break;
        }
        for (const auto &client: net.clients()) {
            client->write(input, [](const asio::error_code &ec, size_t bytes_sent) {
                // Check if message has been sent
            });
        }
    }
    join_threads();

    return 0;
}

On this page