在官方示例中,我如何退出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();发布于 2020-01-15 08:13:40
在一份文件中,有如下所写:
许多用户问他们应该如何停止事件循环。它不是这样做的,你从来没有阻止过它,你让它落空了。通过关闭所有套接字、停止侦听套接字、删除任何计时器等,循环将自动导致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端口
客户断开!
客户断开!
客户断开!
客户断开!
客户断开!
客户断开!
关机!
https://stackoverflow.com/questions/53285876
复制相似问题