forked from leuchter/VS_LET
66 lines
1.8 KiB
Java
66 lines
1.8 KiB
Java
package vs;
|
|
|
|
import java.io.IOException;
|
|
import java.io.PrintWriter;
|
|
import java.net.ServerSocket;
|
|
import java.net.Socket;
|
|
import java.text.DateFormat;
|
|
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 short date and
|
|
* time according to current locale.
|
|
*
|
|
* @author Sandro Leuchter
|
|
*
|
|
*/
|
|
public class TimeTextServer {
|
|
/**
|
|
* 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 TimeTextServer(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 short date and time according to current locale.
|
|
*/
|
|
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();
|
|
String currentTime = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now);
|
|
out.print(currentTime);
|
|
out.flush();
|
|
} catch (IOException e) {
|
|
System.err.println(e);
|
|
}
|
|
}
|
|
} catch (IOException e) {
|
|
System.err.println(e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* main method: entrypoint to run
|
|
*
|
|
* @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 TimeTextServer(Integer.parseInt(args[0])).startServer();
|
|
}
|
|
}
|