Package http

Source Code of http.HttpServer

package http;

import static http.config.Config.getConfig;
import http.log.Log;
import http.utils.command.Command;

import java.io.IOException;
import java.net.ServerSocket;

/**
* The main class of the http server, this class contains a main method for
* starting the app and a serversocket that listen to incomming connections.
*
* @author Dennis Hedegaard
*
*/
public class HttpServer extends Thread {
  /**
   * Default port
   */
  private ServerSocket server;

  public static void main(String[] args) {
    Log.info("Server starting up...");
    new HttpServer();
  }

  /**
   * Calls the {@link #HttpServer(int)} constructor with the default port from
   * a config file, if a config file does not exist, the default is taken from
   * {@link http.global.HttpGlobal#DEFAULT_PORT}.
   *
   * @see #HttpServer(int)
   */
  public HttpServer() {
    this(getConfig().getPort());
  }

  /**
   * Creates a new {@link HttpServer} object and starts a new {@link Thread}
   * that start a {@link ServerSocket} that listens on the port specified. All
   * new connections creates a new {@link HttpSocket} object and starts it as
   * a {@link Thread} after initialization.
   *
   * @param port
   *            The port to listen to.
   */
  public HttpServer(int port) {
    new Command();
    try {
      server = new ServerSocket(port);
      Log.info("Server bound on port: " + server.getLocalPort());
      Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
          try {
            server.close();
            Log.info("Server socket closed.");
          } catch (IOException e) {
            Log.info("Unable to close server socket from hook.");
          }
        }
      });
    } catch (IOException e) {
      Log.severe("Unable to bind server socket on port: " + port);
      System.exit(1);
    }
    start();
  }

  @Override
  public void run() {
    while (!server.isClosed()) {
      Log.fine("Accepting connections...");
      try {
        new HttpSocket(server.accept());
      } catch (IOException e) {
        if (!server.isClosed())
          Log.warning("Unable to accept socket, perhaps a timeout.");
      }
    }
  }
}
TOP

Related Classes of http.HttpServer

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.