Mercurial Hosting > luan
diff src/luan/webserver/Server.java @ 1137:c123ee15f99b
add webserver
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Mon, 29 Jan 2018 18:49:59 -0700 |
parents | |
children | 4189027691b7 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/luan/webserver/Server.java Mon Jan 29 18:49:59 2018 -0700 @@ -0,0 +1,56 @@ +package luan.webserver; + +import java.io.IOException; +import java.net.Socket; +import java.net.ServerSocket; +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 volatile boolean isRunning = false; + private Thread thread; + + 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 { + isRunning = true; + final ServerSocket ss = newServerSocket(); + thread = new Thread("threebody.http.Server") { + public void run() { + try { + while(isRunning) { + Socket socket = ss.accept(); + new Connection(Server.this,socket); + } + } catch(IOException e) { + logger.error("",e); + } + } + }; + thread.start(); + logger.info("started server on port "+port); + } + + public synchronized void stop() { + isRunning = false; + try { + thread.join(); + } catch(InterruptedException e) { + throw new RuntimeException(e); + } + logger.info("stopped server on port "+port); + } + +}