From 98e602f6f40f78b60dd5faac271e697d6c72687b Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Tue, 28 Sep 2021 04:46:02 +0000 Subject: [PATCH] Ensure listening sockets are closed to work around OSX breaking --- .../java/org/ldk/batteries/NioPeerHandler.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/main/java/org/ldk/batteries/NioPeerHandler.java b/src/main/java/org/ldk/batteries/NioPeerHandler.java index faca477f..b722d96d 100644 --- a/src/main/java/org/ldk/batteries/NioPeerHandler.java +++ b/src/main/java/org/ldk/batteries/NioPeerHandler.java @@ -3,6 +3,7 @@ package org.ldk.batteries; import org.ldk.structs.*; import java.io.IOException; +import java.util.LinkedList; import java.net.SocketAddress; import java.net.StandardSocketOptions; import java.nio.Buffer; @@ -239,6 +240,11 @@ public class NioPeerHandler { this.peer_manager.disconnect_by_node_id(their_node_id, false); } + /** + * Before shutdown, we have to ensure all of our listening sockets are closed manually, as they appear + * to otherwise remain open and lying around on OSX (though no other platform). + */ + private LinkedList listening_sockets = new LinkedList(); /** * Binds a listening socket to the given address, accepting incoming connections and handling them on the background * thread. @@ -248,9 +254,13 @@ public class NioPeerHandler { */ public void bind_listener(SocketAddress socket_address) throws IOException { ServerSocketChannel listen_channel = ServerSocketChannel.open(); + listen_channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); listen_channel.bind(socket_address); listen_channel.configureBlocking(false); do_selector_action(() -> listen_channel.register(this.selector, SelectionKey.OP_ACCEPT)); + synchronized(listening_sockets) { + listening_sockets.add(listen_channel); + } } /** @@ -263,6 +273,14 @@ public class NioPeerHandler { try { io_thread.join(); } catch (InterruptedException ignored) { } + synchronized(listening_sockets) { + try { + selector.close(); + for (ServerSocketChannel chan : listening_sockets) { + chan.close(); + } + } catch (IOException ignored) {} + } } /** -- 2.39.5