Skip to content

Websockets: allow setting connection userdata in accept-handler #443

@MichaelSB

Description

@MichaelSB

It would be useful, if one could return userdata in the accept-handler stage of websockets. Currently the accept-handler returns only bool. I suggest something returning std::pair<bool, void*>.
My usecase would be delegation of websocket-messages to specific instances of classes, depending on the WS-Url

CROW_ROUTE(app, "ws/<string>).websocket()
    .onaccept([](const crow::request& req) {
        auto id = get_id_from(req); // some function to get the string in the url
        auto client = get_client_from_id(id);
        
        return client != nullptr;
    })
    .onmessage([](crow::websocket::connection& conn, const std::string message, bool is_binary) {
        // here I have no way to get the client?
    });

returning userdata in a variant of onaccept would enable me to do

CROW_ROUTE(app, "ws/<string>).websocket()
    .onaccept_with_userdata([](const crow::request& req) {
        auto id = get_id_from(req); // some function to get the string in the url
        auto client = get_client_from_id(id);
        
        return { client != nullptr, client };
    })
    .onmessage([](crow::websocket::connection& conn, const std::string message, bool is_binary) {
        auto client = static_cast<MyClient*>(conn.userdata());
        client->handle_message(message, is_binary);
    });

Is there currently any other way doing what I want to do?

Metadata

Metadata

Assignees

Labels

featureCode based project improvement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions