Support dynamic selection of a port using '0' (#1661)

This commit is contained in:
NitrinCloud 2023-01-07 08:39:32 +01:00 committed by GitHub
parent f291437ada
commit aa621021e2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View File

@ -63,6 +63,10 @@ public final class Server {
server.register(selector, SelectionKey.OP_ACCEPT); server.register(selector, SelectionKey.OP_ACCEPT);
this.serverSocket = server; this.serverSocket = server;
this.socketAddress = address; this.socketAddress = address;
if (address instanceof InetSocketAddress && port == 0) {
port = server.socket().getLocalPort();
}
} }
@ApiStatus.Internal @ApiStatus.Internal

View File

@ -14,7 +14,7 @@ public class ServerAddressTest {
@Test @Test
public void inetAddressTest() throws IOException { public void inetAddressTest() throws IOException {
InetSocketAddress address = new InetSocketAddress("localhost", 0); InetSocketAddress address = new InetSocketAddress("localhost", 25565);
var server = new Server(new PacketProcessor()); var server = new Server(new PacketProcessor());
server.init(address); server.init(address);
assertSame(address, server.socketAddress()); assertSame(address, server.socketAddress());
@ -25,6 +25,19 @@ public class ServerAddressTest {
assertDoesNotThrow(server::stop); assertDoesNotThrow(server::stop);
} }
@Test
public void inetAddressDynamicTest() throws IOException {
InetSocketAddress address = new InetSocketAddress("localhost", 0);
var server = new Server(new PacketProcessor());
server.init(address);
assertSame(address, server.socketAddress());
assertEquals(address.getHostString(), server.getAddress());
assertNotEquals(address.getPort(), server.getPort());
assertDoesNotThrow(server::start);
assertDoesNotThrow(server::stop);
}
@Test @Test
public void unixAddressTest() throws IOException { public void unixAddressTest() throws IOException {
UnixDomainSocketAddress address = UnixDomainSocketAddress.of("minestom.sock"); UnixDomainSocketAddress address = UnixDomainSocketAddress.of("minestom.sock");