001package var.sockets.tcp.time;
002
003import java.io.IOException;
004import java.io.PrintWriter;
005import java.net.ServerSocket;
006import java.net.Socket;
007import java.text.DateFormat;
008import java.util.Date;
009
010/**
011 * iterative server for var.sockets.tcp.time Time service. waits for the next
012 * client to connect, then sends time back. format for time is short date and
013 * time according to current locale.
014 *
015 * @author Sandro Leuchter
016 *
017 */
018public class TimeTextServer {
019        /**
020         * port on which this service is currently listening on localhost
021         */
022        private final int port;
023
024        /**
025         * the only constructor for this class
026         *
027         * @param port port on which this service will be listening on localhost
028         */
029        public TimeTextServer(int port) {
030                this.port = port;
031        }
032
033        /**
034         * creates server socket on localhost:port, infinitely handles connections to
035         * clients one after another: waits for the next client to connect, send time
036         * back. format for time is short date and time according to current locale.
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                                        String currentTime = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now);
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
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 TimeTextServer(Integer.parseInt(args[0])).startServer();
064        }
065}