001package var.sockets.tcp.time;
002
003import java.io.IOException;
004import java.io.PrintWriter;
005import java.net.ServerSocket;
006import java.net.Socket;
007import java.util.Date;
008
009/**
010 * iterative server for var.sockets.tcp.time Time service. waits for the next
011 * client to connect, then sends time back. format for time is ASCII
012 * representation of ms since begin of epoch: Jan 1, 1970 00:00:00 GMT.
013 *
014 * @author Sandro Leuchter
015 *
016 */
017public class TimeLongServer {
018        /**
019         * port on which this service is currently listening on localhost
020         */
021        private final int port;
022
023        /**
024         * the only constructor for this class
025         *
026         * @param port port on which this service will be listening on localhost
027         */
028        public TimeLongServer(int port) {
029                this.port = port;
030        }
031
032        /**
033         * creates server socket on localhost:port, infinitely handles connections to
034         * clients one after another: waits for the next client to connect, send time
035         * back. format for time is ASCII representation of ms since begin of epoch: Jan
036         * 1, 1970 00:00:00 GMT.
037         */
038        public void startServer() {
039                try (ServerSocket serverSocket = new ServerSocket(this.port)) {
040                        while (true) {
041                                try (Socket socket = serverSocket.accept();
042                                                PrintWriter out = new PrintWriter(socket.getOutputStream())) {
043                                        Date now = new Date();
044                                        long currentTime = now.getTime();
045                                        out.print(currentTime);
046                                        out.flush();
047                                } catch (IOException e) {
048                                        System.err.println(e);
049                                }
050                        }
051                } catch (IOException e) {
052                        System.err.println(e);
053                }
054        }
055
056        /**
057         * main method: entrypoint to run service
058         *
059         * @param args args[0] must be the port number of the server (int); rest of args
060         *             is ignored
061         */
062        public static void main(String[] args) {
063                new TimeLongServer(Integer.parseInt(args[0])).startServer();
064        }
065}