I wrote server programs which each binds to the same endpoint.
try (var executor = Executors.newVirtualThreadPerTaskExecutor();
var server = new ServerSocket()) {
{
try {
server.setOption(StandardSocketOptions.SO_REUSEADDR, Boolean.TRUE); // IOException
} catch (final UnsupportedOperationException uoe) {
log.error("failed to set {}", StandardSocketOptions.SO_REUSEADDR, uoe);
}
try {
server.setOption(StandardSocketOptions.SO_REUSEPORT, Boolean.TRUE); // IOException
} catch (final UnsupportedOperationException uoe) {
log.error("failed to set {}", StandardSocketOptions.SO_REUSEPORT, uoe);
}
server.setReuseAddress(true); // SocketException
}
{
assert !server.isBound();
server.bind(_Constants.SERVER_ENDPOINT_TO_BIND); // IOException
log.info("bound to {}", server.getLocalSocketAddress());
assert server.isBound();
}
{
__Utils.readQuitAndClose(true, server);
}
while (!server.isClosed()) {
final var client = server.accept(); // IOException
executor.submit(() -> {
try {
log.debug("accepted from {}", client.getRemoteSocketAddress());
for (int r; (r = client.getInputStream().read()) != -1 && !server.isClosed(); ) { // IOException
log.debug("discarding {} received from {}", String.format("0x%1$02X", r),
client.getRemoteSocketAddress());
}
} finally {
client.close();
}
return null;
});
}
}
On macOS multiple processes work. And Windows won't let it.
How can I make Windows allow multiple JVM processes bind on the same socket address?
Here comes what I get when I start a second process (on Windows).
21:36:02.588 [ main] ERROR - failed to set SO_REUSEPORT
java.lang.UnsupportedOperationException: 'SO_REUSEPORT' not supported
at java.base/sun.nio.ch.ServerSocketChannelImpl.setOption(ServerSocketChannelImpl.java:219)
at com.github.onacit.rfc863.Rfc863Tcp2Server.main(Rfc863Tcp2Server.java:25)
Exception in thread "main" java.BindException: Address already in use: bind
at java.base/sun.nio.ch.Net.bind0(Native Method)
at java.base/sun.nio.ch.Net.bind(Net.java:565)
at java.base/sun.nio.ch.ServerSocketChannelImplBind(ServerSocketChannelImpl.java:344)
at java.base/sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:301)
at java.base/java.nio.channels.ServerSocketChannel.bind(ServerSocketChannel.java:224)
at com.github.onacit.rfc863.Rfc863Tcp2Server.main(Rfc863Tcp2Server.java:33)
Process finished with exit code 1