0

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!

Joe Tangana
  • 1
  • 1
  • 1
  • Maybe with `Thread.sleep()`. imho, if you want to send something every minute, it would be easier to make the client ask every minute, it would prevent you from maintaining an opened socket. – Arnaud Denoyelle Mar 07 '16 at 15:11
  • I guess for this purpose node.js will be helpful. because for consistent connection and to handle multiple request at a time node.js works better then any other language. – Munam Tariq Mar 07 '16 at 15:16

1 Answers1

0

I will do like 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);
long mainTime = System.currentTimeMillis()/1000;
while (true) {
    Socket socket = serverSocket.accept();
    OutputStream os = socket.getOutputStream();
    PrintWriter pw = new PrintWriter(os, true);

    if((System.currentTimeMillis()/1000-mainTime)%60>1)){
            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;
    }

}