uSockets icon indicating copy to clipboard operation
uSockets copied to clipboard

us_socket_context_close to close all open sockets for a context

Open amitv87 opened this issue 4 years ago • 3 comments

I see no point to keep the sockets alive after freeing up its context Here are the changes I made to src/socket.c src/context.c

diff --git a/src/context.c b/src/context.c
index 74ec281..6cf6459 100644
--- a/src/context.c
+++ b/src/context.c
@@ -138,6 +138,14 @@ void us_socket_context_free(int ssl, struct us_socket_context_t *context) {
     free((void *) context->options.key_file_name);
     free((void *) context->options.passphrase);

+    context->on_close = NULL;
+    for (context->iterator = context->head; context->iterator;){
+        struct us_socket_t *s = context->iterator;
+        us_socket_close(ssl, s);
+        us_socket_shutdown(ssl, s);
+        if (s == context->iterator) context->iterator = s->next;
+    }
+
 #ifndef LIBUS_NO_SSL
     if (ssl) {
         us_internal_ssl_socket_context_free((struct us_internal_ssl_socket_context_t *) context);
diff --git a/src/socket.c b/src/socket.c
index c201b9c..81d65da 100644
--- a/src/socket.c
+++ b/src/socket.c
@@ -115,7 +115,7 @@ struct us_socket_t *us_socket_close(int ssl, struct us_socket_t *s) {
         /* Any socket with prev = context is marked as closed */
         s->prev = (struct us_socket_t *) s->context;

-        return s->context->on_close(s);
+        return s->context->on_close ? s->context->on_close(s) : s;
     }
     return s;
 }

Possible fix for https://github.com/uNetworking/uWebSockets/issues/809 It makes uWS::TemplatedApp to stop in no time by calling

us_listen_socket_close(ssl, token);
delete uwsApp; // which calls the destructor, uWS::TemplatedApp~TemplatedApp()

amitv87 avatar Jun 24 '20 12:06 amitv87

It makes no sense to free the socket context while still having sockets that belong to it. Doing so is invalid. This change could potentially be applied as a way to force close all sockets. You don't need us_socket_shutdown though, it does nothing after us_socket_close.

ghost avatar Jun 24 '20 14:06 ghost

What would be a better way to force stop a uWS::TemplatedApp instance (stop listening and close all active connections)?

amitv87 avatar Jun 24 '20 14:06 amitv87

us_socket_context_close could be added as a way to close all sockets created with this context. It has nothing with free to do (same could be said about us_loop_free not closing all contexts, etc).

ghost avatar Aug 21 '20 23:08 ghost