import java.io.*; import java.net.*; import java.util.*; public class idleThread extends Thread { // // State information. // private pongIdentity myID; public idleThread(pongIdentity myID) { super(); this.myID = myID; } public void run() { while (true) { long now = System.currentTimeMillis(); // // When pongServer.lastTime is too old, stop the main pongServer // thread from accepting any more client requests. // long diffTime = (now - pongServer.lastTime)/1000; if (diffTime > Pong.MAX_IDLE_TIME) { pongServer.listening = false; pingServer(myID); // kick the server so it'll hop out of the loop return; // kill the idle thread, too! } try { Thread.sleep(5000); } catch (InterruptedException e) {} } } public void pingServer(pongIdentity myID) { // // Attempt to ping myself. At the slightest problem, bailout! // Socket serverSocket = null; ObjectInputStream serialIn = null; ObjectOutputStream serialOut = null; try { serverSocket = new Socket(myID.myIP, myID.myPort); // connect back to myself! } catch (UnknownHostException e) { System.err.println("idleThread: Host unknown : " + e.getMessage()); return; } catch (IOException e) { System.err.println("idleThread: IO exception : " + e.getMessage()); return; } try { serialOut = new ObjectOutputStream(serverSocket.getOutputStream()); serialIn = new ObjectInputStream(serverSocket.getInputStream()); } catch (IOException e) { System.err.println("idleThread: IO exception : " + e.getMessage()); return; } try { serialOut.writeObject(new Integer(Pong.CLIENT_PING)); } catch (IOException e) { System.err.println("idleThread: writeObject: IOException: " + e.getMessage()); return; } int response = 0; try { response = ((Integer) serialIn.readObject()).intValue(); } catch (IOException e) { System.err.println("idleThread: readObject: IOException: " + e.getMessage()); return; } catch (ClassNotFoundException e) { System.err.println("idleThread: readObject: ClassNotFound: " + e.getMessage()); return; } try { serialIn.close(); serialOut.close(); serverSocket.close(); } catch (IOException e) {} } }