diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/Server.java b/src/main/java/com/minecrafttas/mctcommon/networking/Server.java index 9d1d28c5..f6b563eb 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/Server.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/Server.java @@ -30,10 +30,23 @@ public class Server { private final AsynchronousServerSocketChannel serverSocket; private final List clients; + public final int port; + + /** + * Creates and binds a socket on a free port + * + * @param packetIDs Packet ids to use for identifying packets + * @throws Exception + */ + public Server(PacketID[] packetIDs) throws Exception { + this(0, packetIDs); + } + /** - * Create and bind socket + * Create and binds a socket on a specified port * - * @param port Port + * @param port The port to use for the server + * @param packetIDs Packet ids to use for identifying packets * @throws Exception Unable to bind */ public Server(int port, PacketID[] packetIDs) throws Exception { @@ -42,6 +55,11 @@ public Server(int port, PacketID[] packetIDs) throws Exception { this.serverSocket = AsynchronousServerSocketChannel.open(); this.serverSocket.bind(new InetSocketAddress(port)); + InetSocketAddress addr = (InetSocketAddress) this.serverSocket.getLocalAddress(); + this.port = addr.getPort(); + + LOGGER.info(Server, "Server created on port {}", this.port); + // create connection handler this.clients = new ArrayList<>(); this.serverSocket.accept(null, new CompletionHandler() { diff --git a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java index 1ce39bdc..a7046987 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmodClient.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmodClient.java @@ -156,11 +156,10 @@ public void onInitializeClient() { // Starting local server instance try { - TASmod.server = new Server(TASmod.networkingport - 1, TASmodPackets.values()); + TASmod.server = new Server(TASmodPackets.values()); } catch (Exception e) { LOGGER.error("Unable to launch TASmod server: {}", e.getMessage()); } - } private void createFolders() { @@ -228,7 +227,7 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) { boolean local; if (server != null) { ip = "localhost"; - port = TASmod.networkingport - 1; + port = TASmod.server.port; local = true; } else { ip = data.serverIP.split(":")[0]; @@ -290,7 +289,7 @@ private void initializeCustomPacketHandler() { Minecraft mc = Minecraft.getMinecraft(); String IP = "localhost"; - int PORT = TASmod.networkingport - 1; + int PORT = TASmod.server.port; // Get the connection on startup from config String configAddress = config.get(TASmodConfig.ServerConnection);