package primer3;

import java.net.*;
import java.io.*;
import java.util.Date;

public class TimeServer {

	public final static int DEFAULT_PORT = 37;

	public static void main(String[] args) {

		int port = DEFAULT_PORT;
		if (args.length > 0) {
			try {
				port = Integer.parseInt(args[0]);
				if (port < 0 || port >= 65536) {
					System.out.println("Port must be between 0 and 65535");
					return;
				}
			} catch (NumberFormatException ex) {
			}

		}

		// 1900 <-> 1970

		long differenceBetweenEpochs = 2208988800L;

		try (ServerSocket server = new ServerSocket(port)) {

			while (true) {
				try (Socket connection = server.accept();) {
					OutputStream out = connection.getOutputStream();
					Date now = new Date();
					long msSince1970 = now.getTime();
					long secondsSince1970 = msSince1970 / 1000;
					long secondsSince1900 = secondsSince1970 + differenceBetweenEpochs;

					byte[] time = new byte[4];
					time[0] = (byte) (secondsSince1900 >> 24);
					time[1] = (byte) (secondsSince1900 >> 16);
					time[2] = (byte) (secondsSince1900 >> 8);
					time[3] = (byte) (secondsSince1900);

					out.write(time);
					out.flush();

				} catch (IOException ex) {

				}
			}
		} catch (IOException ex) {
			System.err.println(ex);
		}
	}

}
