I'm trying to make a server (that allows multiple client requests) using java sockets. My problem is that I want to make it so when a client sends a request, the server replies giving the server time once every minute. And I want the server to give the time every minute eternally until the client stops the request process (for example, stoping the process in the terminal using "Ctrl+C" key combination). This is the code I already writed, but I'm not sure about how to implement the "give-time-each-minute loop". What's the better way to do it?
public class Server {
public static void main(String args[]) throws IOException {
final int portNumber = Integer.parseInt(args[0]);
System.out.println("Initializing server socket at port" + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
// Here I want to introduce code to give the client the current
// server time once each minute.
// String time = getTime();
// pw.println("Current server time is: " + time);
// ...
pw.close();
socket.close();
}
}
public String getTime(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String stringTime = sdf.format(date);
return stringTime;
}
}
Thank you!