-
Hi, I'm trying to gracefully stop a websocket server but it seems I need to call A simple example in #include "App.h"
#include <iostream>
#include <csignal> // std::signal
struct us_listen_socket_t *gSocket;
int main()
{
int port = 9001;
int nonce = 0;
std::signal(SIGINT, [](int) {
std::cout << "Closing down the server, press again to kill." << std::endl;
std::signal(SIGINT, SIG_DFL);
us_listen_socket_close(0, gSocket);
std::cout << "Is it dead?" << std::endl;
});
struct PerSocketData {
int id;
};
auto app = uWS::App().ws<PerSocketData>("/ws", {
.open = [&nonce](auto *ws) {
ws->subscribe("broadcast");
auto *data = static_cast<PerSocketData *>(ws->getUserData());
data->id = ++nonce;
std::cout << "[open] [" << nonce << "]" << std::endl;
},
.message = [](auto *ws, std::string_view message, uWS::OpCode opCode) {
auto *data = static_cast<PerSocketData *>(ws->getUserData());
std::cout << "[message] [" << data->id << "] " << message << " " << opCode << std::endl;
if (message == "stop") {
std::cout << "closing by a client's request...\n";
us_listen_socket_close(0, gSocket);
ws->close();
} else {
ws->publish("broadcast", message, opCode);
}
}
}).listen(port, [&port](auto *socket) {
std::cout << "Listening on port " << port << std::endl;
gSocket = socket;
}).run();
std::cout << "Graceful exit..." << std::endl;
return 0;
} A client that can run from a console in
Steps:
Expected: What is happening: Could you please point me to the right API on how to gracefully stop the server or whether I have to manually keep all connected clients and call close on every one of them? Thank you |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
us_listen_socket_close shuts the listen socket down. All other established sockets are unaffected. So you need to close them (or gracefully end them) yourself. It had been brought up that we could add us_socket_context_close as a way to close all sockets in a context, but I haven't added it since it is quite easy to do this on your own. |
Beta Was this translation helpful? Give feedback.
-
It would be nice-to-have in cases where everything can be handled just through subscription. Thank you for the clarification. |
Beta Was this translation helpful? Give feedback.
us_listen_socket_close shuts the listen socket down. All other established sockets are unaffected. So you need to close them (or gracefully end them) yourself.
It had been brought up that we could add us_socket_context_close as a way to close all sockets in a context, but I haven't added it since it is quite easy to do this on your own.