Skip to content

Commit

Permalink
Ping thread
Browse files Browse the repository at this point in the history
  • Loading branch information
Brokkonaut committed May 8, 2019
1 parent 0990e31 commit 62fdbdb
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/main/java/de/cubeside/connection/GlobalClient.java
Expand Up @@ -36,6 +36,7 @@ public abstract class GlobalClient implements ConnectionAPI {
private String password;
private volatile boolean running;

private PingThread pingThread;
private ClientThread connection;
private DataOutputStream dos;

Expand All @@ -51,6 +52,11 @@ protected GlobalClient(Logger logger) {
this.players = new HashMap<>();
unmodifiablePlayers = Collections.unmodifiableCollection(players.values());
this.running = true;

pingThread = new PingThread();
pingThread.setName("GlobalConnectionPing");
pingThread.setDaemon(true);
pingThread.start();
}

protected synchronized void setServer(String host, int port, String account, String password) {
Expand All @@ -73,6 +79,27 @@ protected synchronized void setServer(String host, int port, String account, Str
this.connection.start();
}

private class PingThread extends Thread {
private volatile boolean running = true;

@Override
public void run() {
while (running) {
sendPing();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
interrupt();
}
}
}

public void shutdown() {
running = false;
this.interrupt();
}
}

private class ClientThread extends Thread {
private volatile boolean threadRunning;
private Socket socket;
Expand Down Expand Up @@ -372,6 +399,17 @@ protected synchronized void clearServersAndPlayers() {
}
}

protected synchronized void sendPing() {
DataOutputStream dos = this.dos;
if (dos != null) {
try {
dos.writeByte(ClientPacketType.PING.ordinal());
} catch (Exception e) {
logger.log(Level.SEVERE, "Exception sending ping!", e);
}
}
}

protected synchronized void sendPong(ClientThread client) {
DataOutputStream dos = client.localDos;
if (dos != null) {
Expand Down Expand Up @@ -552,6 +590,11 @@ public void shutdown() {
if (localConnection != null) {
localConnection.shutdown();
}
PingThread pingThread = this.pingThread;
if (pingThread != null) {
pingThread.shutdown();
pingThread = null;
}
}

protected abstract void runInMainThread(Runnable r);
Expand Down

0 comments on commit 62fdbdb

Please sign in to comment.