Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help getting basic TLS example to work #1121

Open
machineyearning opened this issue Jan 11, 2024 · 0 comments
Open

Help getting basic TLS example to work #1121

machineyearning opened this issue Jan 11, 2024 · 0 comments

Comments

@machineyearning
Copy link

machineyearning commented Jan 11, 2024

My code below successfully connects to wss://echo.websocket.org, but on_open is never triggered and I don't receive any messages. The output of the program is just:

Connecting to wss://echo.websocket.org
[2024-01-11 00:40:52] [connect] Successful connection
[2024-01-11 00:40:52] [connect] WebSocket Connection 66.241.124.119:443 v-2 "WebSocket++/0.8.2" / 101

My code:

#include <iostream>
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
#include <websocketpp/config/asio_client.hpp>

typedef websocketpp::client<websocketpp::config::asio_tls_client> client;
// typedef websocketpp::client<websocketpp::config::asio_client> client;
typedef websocketpp::lib::shared_ptr<boost::asio::ssl::context> context_ptr;

class websocket_endpoint {
public:
    websocket_endpoint () {
        m_endpoint.clear_access_channels(websocketpp::log::alevel::all);
        m_endpoint.clear_error_channels(websocketpp::log::elevel::all);

        m_endpoint.init_asio();

        // For verbose logging
        m_endpoint.clear_access_channels(websocketpp::log::alevel::all);
        m_endpoint.set_access_channels(websocketpp::log::alevel::connect);
        m_endpoint.set_error_channels(websocketpp::log::elevel::all);

        m_endpoint.set_tls_init_handler(websocketpp::lib::bind(&websocket_endpoint::on_tls_init, this, _1));

        m_endpoint.start_perpetual();

        m_thread.reset(new websocketpp::lib::thread(&client::run, &m_endpoint));
    }

    ~websocket_endpoint() {
        m_endpoint.stop_perpetual();

        if (m_thread) {
            m_thread->join();
        }
    }

	void on_open(websocketpp::connection_hdl hdl) {
        std::cout << "in on_open\n";
		websocketpp::lib::error_code ec;

		// Send a test message
		m_endpoint.send(hdl, "Test message", websocketpp::frame::opcode::text, ec);
		if (ec) {
			std::cout << "Send failed: " << ec.message() << std::endl;
		} else {
			std::cout << "Sent message: Test message" << std::endl;
		}
	}

	void on_close(websocketpp::connection_hdl hdl) {
        std::cout << "in on_close\n";
	}

	void on_fail(websocketpp::connection_hdl hdl) {
        std::cout << "in on_fail\n";
	}

    // TLS Initialization Handler
    context_ptr on_tls_init(websocketpp::connection_hdl hdl) {
        context_ptr ctx(new boost::asio::ssl::context(boost::asio::ssl::context::tlsv12));

        ctx->set_options(boost::asio::ssl::context::default_workarounds |
                         boost::asio::ssl::context::no_sslv2 |
                         boost::asio::ssl::context::no_sslv3 |
                         boost::asio::ssl::context::single_dh_use);
        ctx->set_verify_mode(boost::asio::ssl::verify_none); // Disable certificate verification

        return ctx;
    }

    void on_message(websocketpp::connection_hdl, client::message_ptr msg) {
        std::cout << "in on_message!\n";
        std::cout << msg->get_payload() << std::endl;
        if (msg->get_opcode() == websocketpp::frame::opcode::text) {
            std::string payload = msg->get_payload();
            // Now 'payload' contains your JSON string
            std::cout << "Received message: " << payload << std::endl;

            // If you want to parse this JSON, you can use a JSON library like nlohmann/json
        } else {
            std::cout << "error\n";
        }
    }

    void connect(std::string const & uri) {
        websocketpp::lib::error_code ec;

        client::connection_ptr con = m_endpoint.get_connection(uri, ec);

        if (ec) {
            std::cout << "Could not create connection because: " << ec.message() << std::endl;
            return;
        }

        m_endpoint.set_message_handler(websocketpp::lib::bind(
            &websocket_endpoint::on_message,
            this,
            _1,
            _2
        ));

		// Set the on_open handler
		m_endpoint.set_open_handler(websocketpp::lib::bind(
			&websocket_endpoint::on_open,
			this,
			_1
		));

		m_endpoint.set_close_handler(websocketpp::lib::bind(
			&websocket_endpoint::on_close,
			this,
			_1
		));

		m_endpoint.set_fail_handler(websocketpp::lib::bind(
			&websocket_endpoint::on_fail,
			this,
			_1
		));

        m_endpoint.connect(con);
    }

private:
    client m_endpoint;
    websocketpp::lib::shared_ptr<websocketpp::lib::thread> m_thread;

};

int main() {
    websocket_endpoint endpoint;

    std::string uri = "wss://echo.websocket.org";
    std::cout << "Connecting to " << uri << std::endl;

    endpoint.connect(uri);
    std::cin.get();
}

I'm on an M2 Macbook, and I'm running this to compile the program:
g++ -I/opt/homebrew/Cellar/boost/1.83.0/include -L/opt/homebrew/Cellar/boost/1.83.0/lib -lboost_system -lboost_thread-mt -DBOOST_BIND_GLOBAL_PLACEHOLDERS -lboost_chrono -lboost_random -I/opt/homebrew/Cellar/openssl@3/3.2.0_1/include -L/opt/homebrew/Cellar/openssl@3/3.2.0_1/lib -lssl -lcrypto -I. test.cpp

I confirmed in Python that this websocket url does send data:

import asyncio
import websockets

async def listen_to_websocket(uri):
    async with websockets.connect(uri) as websocket:
        while True:
            message = await websocket.recv()
            print(message)

asyncio.run(listen_to_websocket('wss://echo.websocket.org'))

This prints out Request served by 1781505b56ee58

Have spent a couple hours getting to this point (compilation/linking errors and issues with TLS handshake). Hopefully I am close to getting this to work...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant