package vs;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class WebServer {
	public void start() {
		try (ServerSocket serverSocket = new ServerSocket(8000)) {
			System.out.println("WebServer gestartet ...");
			while (true) {
				Socket socket = serverSocket.accept();
				new WebThread(socket).start();
			}
		} catch (IOException e) {
			System.err.println(e);
		}
	}

	private class WebThread extends Thread {
		private Socket socket;

		public WebThread(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			SocketAddress socketAddress = socket.getRemoteSocketAddress();
			System.err.println("Verbindung zu " + socketAddress + " aufgebaut");
			try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
				String input;
				while (null != (input = in.readLine())) {
					System.out.println(input);
				}
			} catch (Exception e) {
				System.err.println(e);
			} finally {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.err.println("Verbindung zu " + socketAddress + " abgebaut");
			}
		}

	}

	public static void main(String[] args) {
		new WebServer().start();
	}
}
