如何优雅地停止uWebSockets服务器?

时间:2018-11-13 16:51:02

标签: c++ linux websocket uwebsockets

在官方示例中,如何退出run()通话?例如,在收到信号之后。

uWS::SSLApp({

    /* There are tons of SSL options */
    .cert_file_name = "cert.pem",
    .key_file_name = "key.pem"

}).onGet("/", [](auto *res, auto *req) {

    /* Respond with the web app on default route */
    res->writeStatus("200 OK")
       ->writeHeader("Content-Type", "text/html; charset=utf-8")
       ->end(indexHtmlBuffer);

}).onWebSocket<UserData>("/ws/chat", [&](auto *ws, auto *req) {

    /* Subscribe to topic /chat */
    ws->subscribe("chat");

}).onMessage([&](auto *ws, auto message, auto opCode) {

    /* Parse incoming message according to some protocol & publish it */
    if (seemsReasonable(message)) {
        ws->publish("chat", message);
    } else {
        ws->close();
    }

}).onClose([&](auto *ws, int code, auto message) {

    /* Remove websocket from this topic */
    ws->unsubscribe("chat");

}).listen("localhost", 3000, 0).run();

1 个答案:

答案 0 :(得分:0)

a documentation中,写有以下内容:

许多用户问他们应该如何停止事件循环。这不是完成的方式,您永远都不要停止它,而要让它失败。通过关闭所有套接字,停止监听套接字,删除任何计时器等,循环将自动导致App.run正常返回,而不会发生内存泄漏。

由于该应用本身在RAII的控制之下,一旦阻塞的.run调用返回并且该应用超出范围,则所有内存将正常删除。

因此,这意味着您必须释放函数内部的每个源。所以这个:

    void testThread() {
        std::this_thread::sleep_for(15s);
        us_listen_socket_close(0, listen_socket);
    }

    int main()
    {
        std::thread thread(testThread);
        uWS::App app;
        /* Very simple WebSocket broadcasting echo server */
        app.ws<PerSocketData>("/*", {
            /* Settings */
            .compression = uWS::SHARED_COMPRESSOR,
            .maxPayloadLength = 16 * 1024 * 1024,
            .idleTimeout = 10,
            .maxBackpressure = 1 * 1024 * 1204,
            /* Handlers */
            .open = [](auto* ws, auto* req) {
                /* Let's make every connection subscribe to the "broadcast" topic */
                ws->subscribe("broadcast");
            },
            .message = [](auto* ws, std::string_view message, uWS::OpCode opCode) {
            },
            .drain = [](auto* ws) {
                /* Check getBufferedAmount here */
            },
            .ping = [](auto* ws) {

            },
            .pong = [](auto* ws) {

            },
            .close = [](auto* ws, int code, std::string_view message) {
                std::cout << "Client disconnect!" << std::endl;

                /* We automatically unsubscribe from any topic here */
            }
            }).listen(9001, [](auto* token) {
                listen_socket = token;
                if (token) {
                    std::cout << "Listening on port " << 9001 << std::endl;
                }
                });
            app.run();

            std::cout << "Shutdown!" << std::endl;

在调用testThread之后,服务器应退出(如果未连接任何客户端,否则,您还应断开已连接的客户端(套接字))并在run()行之后继续。断开客户端连接后,我的输出如下:

在9001港口监听

客户端断开连接!

客户端断开连接!

客户端断开连接!

客户端断开连接!

客户端断开连接!

客户端断开连接!

关机!