Fix & cleanup OpenToLAN

This commit is contained in:
TheMode 2021-08-21 10:12:55 +02:00
parent 9ec257ed3d
commit 23c76bc799
2 changed files with 44 additions and 47 deletions

View File

@ -59,12 +59,9 @@ public class OpenToLAN {
*/
public static boolean open(@NotNull OpenToLANConfig config) {
Objects.requireNonNull(config, "config");
if (socket != null) return false;
if (socket != null) {
return false;
} else {
int port = config.port;
if (port == 0) {
try {
port = NetworkUtils.getFreePort();
@ -87,7 +84,6 @@ public class OpenToLAN {
.schedule();
return true;
}
}
/**
* Closes the server to LAN.
@ -95,18 +91,14 @@ public class OpenToLAN {
* @return {@code true} if it was closed, {@code false} if it was already closed
*/
public static boolean close() {
if (socket == null) {
return false;
} else {
if (socket == null) return false;
task.cancel();
socket.close();
task = null;
socket = null;
return true;
}
}
/**
* Checks if the server is currently opened to LAN.
@ -121,7 +113,7 @@ public class OpenToLAN {
* Performs the ping.
*/
private static void ping() {
if (MinecraftServer.getServer().getPort() != 0) {
if (!MinecraftServer.getServer().isOpen()) return;
if (packet == null || eventCooldown.isReady(System.currentTimeMillis())) {
final ServerListPingEvent event = new ServerListPingEvent(OPEN_TO_LAN);
EventDispatcher.call(event);
@ -132,12 +124,10 @@ public class OpenToLAN {
eventCooldown.refreshLastUpdate(System.currentTimeMillis());
}
try {
socket.send(packet);
} catch (IOException e) {
LOGGER.warn("Could not send Open to LAN packet!", e);
}
}
}
}

View File

@ -5,6 +5,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
@ -41,6 +42,12 @@ public final class Server {
}
public void start(SocketAddress address) throws IOException {
if (address instanceof InetSocketAddress) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) address;
this.address = inetSocketAddress.getHostString();
this.port = inetSocketAddress.getPort();
} // TODO unix domain support
this.serverSocket = ServerSocketChannel.open();
serverSocket.bind(address);
serverSocket.configureBlocking(false);