Close weboscket-connections from server-side (C++) #1528
-
Hello! I'm trying to shut down the websocket-server correctly. Is it possible to close/abort all websocket-connections from server-side? The applications hangs on joining the websocket-thread and the following code does not close the application "quite fast" and completely:
I've checked all discussions and docs but I didn't find a way how to close all connections from server-side for example in case a system need to reboot. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
It's a bit silly but you have to track your connections yourself. Something like this will make it shut down properly (this is an aera that needs improvement - ideally it should be app.close()): std::unordered_set<void *> connectionSet; // Track your connections // When you want to close: |
Beta Was this translation helpful? Give feedback.
-
Hoping this will save someone some trouble: The accepted solution is wrong, as it creates a use-after-free issue. When Also, this solution ignores what happens with in-progress transfers. You likely want to allow those transfers to complete, or have some controlled way to close the sockets on timeouts. To do this, you should only I suggest the following is a cleaner way to end responses: /* The exit code tells any waiting handler why the socket was closed. */
#define APP_EXIT 100
for (auto it = connectionSet.begin(); it != connectionSet.end();) {
/* The unresponded sockets will be closed by the respective handlers after responding
* make sure to make the last write res->end("blah", true), where "true" means closeConnection
* when transfer is complete.
*/
if ((*it)->hasResponded())
/* advance the iterator to the next position before erase() the current */
us_socket_close(false, (us_socket_t*) *it++, APP_EXIT, nullptr);
else
it++;
} |
Beta Was this translation helpful? Give feedback.
It's a bit silly but you have to track your connections yourself. Something like this will make it shut down properly (this is an aera that needs improvement - ideally it should be app.close()):
std::unordered_set<void *> connectionSet;
// Track your connections
app.filter([&connectionSet](auto *s, int diff){
if (diff > 0) {
connectionSet.insert((void *) s);
} else {
connectionSet.erase((void *) s);
}
})
// When you want to close:
for (auto *s : connectionSet) {
us_socket_close(SSL, (struct us_socket_t *) s);
}