Skip to content

Websockets cause segfault when closing from server side #446

@MichaelSB

Description

@MichaelSB

When I call crow::websocket::connection::close() server side, my application segfaults. Minimal example showing the problem I have:

#include "crow.h"
#include "crow/http_response.h"
#include "crow/json.h"
#include "crow/logging.h"
#include "crow/routing.h"
#include "crow/websocket.h"

int main(int, char**)
{
    crow::SimpleApp app;

    crow::websocket::connection* wsconn = nullptr;

    CROW_ROUTE(app, "/")([](const crow::request& req) {
        crow::response resp;
        resp.set_static_file_info("index.html");
        return resp;
    });

    CROW_ROUTE(app, "/ws").websocket()
        .onopen([&](crow::websocket::connection& conn) {
            wsconn = &conn;
        });
        .onclose([](crow::websocket::connection& conn, const std::string& reason) {
            CROW_LOG_INFO << reason;
        });

    CROW_ROUTE(app, "/disconnect")([&](const crow::request& req) {
        if(wsconn) {
            wsconn->close();
            wsconn = nullptr;
        }
        return crow::response(200);
    });

    app.port(18080).multithreaded().run();

    return 0;
}

index.html used:

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="UTF-8">
  <title>Main</title>
</head>
<body>
<button type="button" onclick="disconnect()">Disconnect</button>
<script>
    var ws = new WebSocket("ws://localhost:18080/ws");

    function disconnect() {
        var req = new XMLHttpRequest();
        req.open("GET", "http://localhost:18080/disconnect", false);
        req.send(null);
    }
</script>
</body>
</html>

So the frontend opens a websocket and when the disconnect-button is clicked, the server should close it. I guess, I am doing something wrong, besides multiple connections cannot be handled in this example :) The onclose()-handler is called, I get reason logged. And then segfault.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions