Jump to content

ServerDaemon.java

From EDM2
import java.net.*;
import java.io.*;

public class ServerDaemon implements Runnable {

    private Thread       daem;
    private Server       owner;
    private int          port;
    private ServerSocket sock;

    // constructor
    public ServerDaemon(Server s, int p) throws Exception {
        owner = s;
        port  = p;
        sock  = new ServerSocket(port);

        daem  = new Thread(this);
        daem.start();
    }

    // run is called from JVM upon a call to start
    public void run() {
        long upTime = 1000   // milliseconds
                      * 60   // * seconds
                      * 5L;  // * minutes = time in minutes
        int stopLoop = 0; // used to avoid severe errors

        while (stopLoop < 100) {
            // used to see if severe error occurs
            long startTime = System.currentTimeMillis();

            try {
                if (sock == null) { // if error had occurred
                    sock  = new ServerSocket(port);
                }

                while (true) { // listen for connections
                    Socket newCon = sock.accept();

                    // create a socket object for that conn.
                    MyServerSocket s = new MyServerSocket(newCon, owner);
                    s.start();

                    // add the new connection to the vector
                    owner.addMySocket(s);
                }

            } catch (Exception e) {
                e.printStackTrace();
                sock = null;

                if ((System.currentTimeMillis() - startTime)
                    < upTime) {

                    ++stopLoop;
                    try {
                        /* take a nap with. The nap time
                         * will increase up to as worst 99
                         * min's. We hope that the network
                         * error will be gone by that time,
                         * summing up to almost 3.5 days.*/
                        Thread.sleep(60000L // one minute
                                     * stopLoop);

                    } catch (Exception exc) {}

                } else {
                    stopLoop = 0; // erase earlier errors
                }
            } // try/catch ends
        } // while ends

        System.out.println("ERROR in ServerDaemon. Exiting");
        System.exit(0);

    }
}