view src/luan/webserver/Server.java @ 1175:d6d0bd05ad8c

exit on bind conflict, serve "127.0.0.1" for serve_for_nginx
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 12 Feb 2018 14:55:28 -0700
parents 0f59eab45f3d
children 79b1e9ffd0c0
line wrap: on
line source

package luan.webserver;

import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Server {
	private static final Logger logger = LoggerFactory.getLogger(Server.class);

	public final int port;
	public final Handler handler;
	private static final ExecutorService exec = Executors.newCachedThreadPool();

	public Server(int port,Handler handler) {
		this.port = port;
		this.handler = handler;
	}

	protected ServerSocket newServerSocket() throws IOException {
		return new ServerSocket(port);
	}

	public synchronized void start() throws IOException {
		final ServerSocket ss = newServerSocket();
		exec.execute(new Runnable(){public void run() {
			try {
				while(!exec.isShutdown()) {
					final Socket socket = ss.accept();
					exec.execute(new Runnable(){public void run() {
						Connection.handle(Server.this,socket);
					}});
				}
			} catch(IOException e) {
				logger.error("",e);
			}
		}});
		logger.info("started server on port "+port);
	}

	public synchronized boolean stop(long timeoutSeconds) {
		try {
			exec.shutdownNow();
			boolean stopped = exec.awaitTermination(timeoutSeconds,TimeUnit.SECONDS);
			if(stopped)
				logger.info("stopped server on port "+port);
			else
				logger.warn("couldn't stop server on port "+port);
			return stopped;
		} catch(InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

	public static class Local extends Server {
		public Local(int port,Handler handler) {
			super(port,handler);
		}

		protected ServerSocket newServerSocket() throws IOException {
			return new ServerSocket(port,0,InetAddress.getByName("127.0.0.1"));
		}
	}
}