package vs;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * iterative server for var.sockets.tcp.time Time service. waits for the next
 * client to connect, then sends time back. format for time is ASCII
 * representation of ms since begin of epoch: Jan 1, 1970 00:00:00 GMT.
 *
 * @author Sandro Leuchter
 *
 */
public class TimeLongServer {
	/**
	 * port on which this service is currently listening on localhost
	 */
	private final int port;

	/**
	 * the only constructor for this class
	 *
	 * @param port port on which this service will be listening on localhost
	 */
	public TimeLongServer(int port) {
		this.port = port;
	}

	/**
	 * creates server socket on localhost:port, infinitely handles connections to
	 * clients one after another: waits for the next client to connect, send time
	 * back. format for time is ASCII representation of ms since begin of epoch: Jan
	 * 1, 1970 00:00:00 GMT.
	 */
	public void startServer() {
		try (ServerSocket serverSocket = new ServerSocket(this.port)) {
			while (true) {
				try (Socket socket = serverSocket.accept();
						PrintWriter out = new PrintWriter(socket.getOutputStream())) {
					Date now = new Date();
					long currentTime = now.getTime();
					out.print(currentTime);
					out.flush();
				} catch (IOException e) {
					System.err.println(e);
				}
			}
		} catch (IOException e) {
			System.err.println(e);
		}
	}

	/**
	 * main method: entrypoint to run service
	 *
	 * @param args args[0] must be the port number of the server (int); rest of args
	 *             is ignored
	 */
	public static void main(String[] args) {
		new TimeLongServer(Integer.parseInt(args[0])).startServer();
	}
}
