Skip to content

Commit

Permalink
Removed timeout system
Browse files Browse the repository at this point in the history
  • Loading branch information
ScribbleTAS committed Oct 24, 2023
1 parent 9e4ab6d commit 149dc1b
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 120 deletions.
92 changes: 25 additions & 67 deletions src/main/java/com/minecrafttas/common/server/Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import java.nio.channels.CompletionHandler;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.logging.log4j.Level;
Expand Down Expand Up @@ -46,13 +47,6 @@ public class Client {

private Side side;

/* =Timeout checking= */
private long timeout;
private TimerTask timertask;
/**
* Timestamp of the last packet that was received
*/
private long timeAtLastPacket;
private ClientCallback callback;
/**
* True, if the client is connected to a local "integrated" server. Special
Expand All @@ -72,13 +66,11 @@ public enum Side {
* @param host Host
* @param port Port
* @param packetIDs A list of PacketIDs which are registered
* @param uuid The UUID of the client
* @param timout Time since last packet when the client should disconnect
* @param local Property to check, if the server is a local server. If yes,
* special conditions may apply
* @throws Exception Unable to connect
*/
public Client(String host, int port, PacketID[] packetIDs, String name, long timeout, boolean local) throws Exception {
public Client(String host, int port, PacketID[] packetIDs, String name, boolean local) throws Exception {
LOGGER.info(Client, "Connecting server to {}:{}", host, port);
this.socket = AsynchronousSocketChannel.open();
this.socket.connect(new InetSocketAddress(host, port)).get();
Expand All @@ -93,7 +85,6 @@ public Client(String host, int port, PacketID[] packetIDs, String name, long tim

this.createHandlers();

this.timeout = timeout;
this.callback = (client) -> {
EventDisconnectClient.fireDisconnectClient(client);
};
Expand All @@ -113,10 +104,9 @@ public Client(String host, int port, PacketID[] packetIDs, String name, long tim
*
* @param socket Socket
*/
public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs, long timeout, ClientCallback callback) {
public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs, ClientCallback callback) {
this.socket = socket;
this.callback = callback;
this.timeout = timeout;
try {
this.socket.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
this.socket.setOption(StandardSocketOptions.TCP_NODELAY, true);
Expand All @@ -125,7 +115,6 @@ public Client(AsynchronousSocketChannel socket, PacketID[] packetIDs, long timeo
}
this.packetIDs = packetIDs;
this.createHandlers();
// this.registerTimeoutTask(100);
this.side = Side.SERVER;
}

Expand Down Expand Up @@ -187,20 +176,35 @@ public void completed(Integer result, Object attachment) {
readBuffer.clear().limit(4);
socket.read(readBuffer, null, this);
} catch (Throwable exc) {
LOGGER.error("Unable to read packet!", exc);
if(exc instanceof ExecutionException && !isClosed()) {
LOGGER.debug(getLoggerMarker(), "{} terminated the connection!", getOppositeSide().name());
try {
close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
LOGGER.error(getLoggerMarker(), "Unable to read packet!", exc);
}
}

@Override
public void failed(Throwable exc, Object attachment) {
if (exc instanceof AsynchronousCloseException || exc instanceof IOException) {
LOGGER.warn(getLoggerMarker(), "{} terminated the connection!", (side == Side.CLIENT ? Side.CLIENT : Side.SERVER).name());
if(isClosed()) {
return;
}
LOGGER.debug(getLoggerMarker(), "{} terminated the connection!", getOppositeSide().name());
try {
close();
} catch (IOException e) {
LOGGER.error(getLoggerMarker(), "Attempted to close connection but failed", e);
}
} else {
if(isClosed()) {
return;
}
LOGGER.error(getLoggerMarker(), "Something went wrong, terminating connection!", exc);
try {
close();
Expand Down Expand Up @@ -256,13 +260,16 @@ private void close() throws IOException {
callback.onClose(this);
}

this.timertask.cancel();
this.socket.close();
}

private Marker getLoggerMarker() {
return side == Side.CLIENT ? Client : Server;
}

private Side getOppositeSide() {
return side == Side.CLIENT ? Side.SERVER : Side.CLIENT;
}

/**
* Sends then authentication packet to the server
Expand Down Expand Up @@ -293,11 +300,10 @@ private void handle(ByteBuffer buf) {
completeAuthentication(buf);
return;
} else if (id == -2) {
LOGGER.debug(getLoggerMarker(), "Disconnected by the {}", side.name(), (side == Side.CLIENT ? Side.CLIENT : Side.SERVER).name());
LOGGER.info(getLoggerMarker(), "Disconnected by the {}", getOppositeSide().name());
close();
return;
}
timeAtLastPacket = System.currentTimeMillis();
PacketID packet = getPacketFromID(id);
PacketHandlerRegistry.handle(side, packet, buf, this.username);
} catch (PacketNotImplementedException | WrongSideException e) {
Expand Down Expand Up @@ -329,54 +335,6 @@ public String getRemote() throws IOException {
return ip + ":" + port;
}

/**
* Registers a task for the timer, that checks if this socket is timed out.
*
* <p>
* The interval is 1 second
*
*/
private void registerTimeoutTask(long delay) {
TimerTask task = new TimerTask() {

@Override
public void run() {
if (checkTimeout()) {
disconnect();
}
}

};
this.timertask = task;
timeAtLastPacket = System.currentTimeMillis();
timeoutTimer.scheduleAtFixedRate(task, delay, 1000);
}

private boolean checkTimeout() {
long timeSinceLastPacket = System.currentTimeMillis() - timeAtLastPacket;

System.out.println(timeSinceLastPacket);

if (timeSinceLastPacket > timeout) {
LOGGER.warn(getLoggerMarker(), "Client {} timed out after {}ms", getId(), timeSinceLastPacket);
return true;
} else if (timeSinceLastPacket < 0) {
LOGGER.error(getLoggerMarker(), "Time ran backwards? Timing out client {}: {}ms", getId(), timeSinceLastPacket);
return true;
}

return false;
}

public void setTimeoutTime(long timeout) {
this.timeAtLastPacket = System.currentTimeMillis();
this.timeout = timeout;
}

public long getTimeoutTime() {
return this.timeout;
}

public boolean isLocal() {
return this.local;
}
Expand Down
8 changes: 1 addition & 7 deletions src/main/java/com/minecrafttas/common/server/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public void completed(AsynchronousSocketChannel clientSocket, Object attachment)
LOGGER.debug(Server, "Disconnecting player from server. Server now has {} connections", getClients().size());
};

Client newclient = new Client(clientSocket, packetIDs, 10000, callback);
Client newclient = new Client(clientSocket, packetIDs, callback);
clients.add(newclient);

serverSocket.accept(null, this);
Expand Down Expand Up @@ -132,12 +132,6 @@ public void disconnectAll() {
}
}

public void setTimeoutTime(long timeout) {
for (Client client : getClients()) {
client.setTimeoutTime(timeout);
}
}

/**
* Try to close socket
*
Expand Down
4 changes: 0 additions & 4 deletions src/main/java/com/minecrafttas/tasmod/TASmod.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import com.minecrafttas.tasmod.commands.CommandSavestate;
import com.minecrafttas.tasmod.commands.CommandTickrate;
import com.minecrafttas.tasmod.ktrng.KillTheRNGHandler;
import com.minecrafttas.tasmod.networking.ServerModifications;
import com.minecrafttas.tasmod.networking.TASmodPackets;
import com.minecrafttas.tasmod.playback.PlaybackControllerServer;
import com.minecrafttas.tasmod.savestates.SavestateHandlerServer;
Expand Down Expand Up @@ -63,8 +62,6 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop{

public static final Scheduler tickSchedulerServer = new Scheduler();

public static final ServerModifications servermod = new ServerModifications();

public static Server server;

public static final int networkingport = 8999;
Expand Down Expand Up @@ -92,7 +89,6 @@ public void onInitialize() {
EventListenerRegistry.register(ticksyncServer);
EventListenerRegistry.register(tickratechanger);
EventListenerRegistry.register(ktrngHandler);
EventListenerRegistry.register(servermod);

// Register packet handlers
LOGGER.info(LoggerMarkers.Networking, "Registering network handlers");
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/minecrafttas/tasmod/TASmodClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public void onClientInit(Minecraft mc) {
})));
blockedKeybindings.add(keybindManager.registerKeybind(new Keybind("Various Testing2", "TASmod", Keyboard.KEY_F7, () -> {
try {
TASmodClient.client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getProfile().getName(), 10000, true);
TASmodClient.client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getProfile().getName(), true);
} catch (Exception e) {
e.printStackTrace();
}
Expand Down Expand Up @@ -246,7 +246,7 @@ public void onPlayerJoinedClientSide(EntityPlayerSP player) {
gameLoopSchedulerClient.add(()->{
try {
// connect to server and authenticate
client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername(), 10000, local); //TODO set timeout by tickrate
client = new Client(IP, PORT, TASmodPackets.values(), mc.getSession().getUsername(), local); //TODO set timeout by tickrate
} catch (Exception e) {
LOGGER.error("Unable to connect TASmod client: {}", e.getMessage());
e.printStackTrace();
Expand All @@ -269,7 +269,7 @@ public GuiScreen onOpenGui(GuiScreen gui) {
Minecraft mc = Minecraft.getMinecraft();
try {
// connect to server and authenticate
client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), 10000, true);
client = new Client("localhost", TASmod.networkingport-1, TASmodPackets.values(), mc.getSession().getUsername(), true);
} catch (Exception e) {
LOGGER.error("Unable to connect TASmod client: {}", e.getMessage());
}
Expand Down

This file was deleted.

2 changes: 1 addition & 1 deletion src/test/java/common/server/ServerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ static void setUpBeforeClass() throws Exception {
}

try {
client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), "TASBot", 3000, true);
client = new Client("127.0.0.1", 25566, TestPacketIDs.values(), "TASBot", true);
} catch (Exception e) {
e.printStackTrace();
}
Expand Down

0 comments on commit 149dc1b

Please sign in to comment.