package uk.ac.vamsas.client.picking; import java.io.*; import java.net.*; import java.util.logging.*; import org.apache.commons.logging.Log; /** * Server class that listens for incoming connections on a predefined port. */ class PickServer extends Thread { private Log logger = org.apache.commons.logging.LogFactory.getLog(uk.ac.vamsas.client.picking.PickServer.class); // The port number we'll listen on static final int PORT = 53782; private ServerSocket serverSocket; // Set to true once the server is established private boolean isServer = false; private SocketManager manager; /** * Constructs a new instance of the server (but doesn't start it). * @param manager a reference to the pick manager that owns this server */ PickServer(SocketManager manager) { this.manager = manager; } /** * Returns true if this server instance is running. * Return true if this server instance is running */ boolean isServer() { return isServer; } /** * Attempts to create the server by opening a server socket on the port. * @return true if the server was created; false otherwise */ boolean createServer() { try { serverSocket = new ServerSocket(PORT); start(); return isServer = true; } catch (IOException e) { //logger.info("SERVER: " + e); return false; } } /** * state of server thread - running or not running */ private boolean running=false; /** * condition for server thread to stop */ private boolean enabled=true; public void haltServer() { // TODO: FIX THIS METHOD if (!running || !enabled) { logger.debug("PickServer is not running or already requested to halt."); return; } logger.debug("Disabling pick server."); enabled=false; while (running) { try { serverSocket.close(); } catch (Exception e) { } try { Thread.sleep(5); } catch (Exception e) { } } logger.debug("Pick server has stopped."); } /** * Thread listening method - loops indefinitely listening for connections. * When one is received, the socket object is passed to the manager so it * can make a full client connection for further comms. */ public void run() { enabled=true; running=true; //logger.info("SERVER: listening on " + PORT + " - SERVER"); // Loop forever, accepting connectons from other clients // TODO: terminate the server when haltServer is called (fails tests currently) while (enabled) { try { Socket socket = serverSocket.accept(); //logger.info("SERVER: connection detected"); manager.addEndPoint(socket); } catch (IOException e) {} } running=false; manager.haltManager(); } }