1

I am trying to connect to a secure websocket using asio.

This example will work for an ip address:

#include <iostream>
#include <asio.hpp>
int main() {
    asio::error_code ec;

    asio::io_context context;

    asio::io_context::work idleWork(context);

    asio::ip::tcp::endpoint endpoint(asio::ip::make_address("51.38.81.49", ec), 80);

    asio::ip::tcp::socket socket(context);

    socket.connect(endpoint, ec);

    if (!ec) {
        std::cout << "Connected!" << std::endl;
    } else {
        std::cout << "Failed to connect to address: \n" << ec.message() << std::endl;
    }
return 0;
}

but how would I change it so I connect to "wss://api2.example.com"?

EDIT:

Thanks for your answer karastojko - it seems to get me some of the way. I would though like to know if I am actually connected to the server, so I have updated my example with your input, added a working WSS which I know will answer and created read and write.

#include <asio.hpp>
#include <asio/ts/buffer.hpp>

std::vector<char> vBuffer(1 * 1024);

// This should output the received data
void GrabSomeData(asio::ip::tcp::socket& socket) {
    socket.async_read_some(asio::buffer(vBuffer.data(), vBuffer.size()),
        [&](std::error_code ec, std::size_t lenght) {
            if (!ec) {
                std::cout << "\n\nRead " << lenght << " bytes\n\n";

                for (int i = 0; i < lenght; i++)
                    std::cout << vBuffer[i];

                GrabSomeData(socket);
            }
        }
    );
}

int main() {

    asio::error_code ec;

    asio::io_context context;

    asio::io_context::work idleWork(context);

    std::thread thrContext = std::thread([&]() { context.run(); });
    
    // I hope this is what you meant
    asio::ip::tcp::resolver res(context);
    asio::ip::tcp::socket socket(context);
    asio::connect(socket, res.resolve("echo.websocket.org", std::to_string(443)));

    // Check the socket is open
    if (socket.is_open()) {
        // Start to output incoming data
        GrabSomeData(socket);

        // Send data to the websocket, which should be sent back
        std::string sRequest = "Echo";
        socket.write_some(asio::buffer(sRequest.data(), sRequest.size()), ec);
        
        // Wait some time, so the data is received
        using namespace std::chrono_literals;
        std::this_thread::sleep_for(20000ms);

        context.stop();
        if (thrContext.joinable()) thrContext.join();
    }

    return 0;
}
MTN
  • 11
  • 4

1 Answers1

1

For that purpose use the resolver class:

    tcp::resolver res(context);
    asio::ip::tcp::socket socket(context);
    boost::asio::connect(socket, res.resolve("api2.example.com", 80));
karastojko
  • 1,156
  • 9
  • 14