Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions src/main/java/com/minecrafttas/mctcommon/networking/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,23 @@ public class Server {
private final AsynchronousServerSocketChannel serverSocket;
private final List<Client> 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 {
Expand All @@ -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<AsynchronousSocketChannel, Object>() {
Expand Down
7 changes: 3 additions & 4 deletions src/main/java/com/minecrafttas/tasmod/TASmodClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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);
Expand Down