
import java.net.*;
import java.io.*;
import java.util.*;

class Client { // Every java program begins like this
  public static void main(String[] args) throws Exception {

    //basic client setup copied from previous program:
    String host = "localhost";
    int port = 12345;
    Socket s = new Socket(host, port);

    //We send the server some random time, which will be our offset
    Random rnd = new Random();

    Integer h = rnd.nextInt(24);
    String hh;
    if (h < 9) {
      hh = "0" + h; //pad with zero, so it looks like a real timestamp
    } else {
      hh = h.toString(); //no padding necessary
    }

    //same as above for minute, except 60 not 24 is max
    Integer m = rnd.nextInt(60);
    String mm;
    if (m < 9) {
      mm = "0" + m;
    } else {
      mm = m.toString();
    }

    String offset = hh + ":" + mm;

    //log:
    System.out.
            println("Getting time from server, with offset " + offset + "...");

    //IO:
    Scanner sc = new Scanner(s.getInputStream());
    PrintWriter pw = new PrintWriter(s.getOutputStream());

    //send
    pw.println(offset);
    pw.flush();

    //receive:
    String result = sc.nextLine();

    //log:
    System.out.println("Result: " + result);

    String[] parts = result.split(":");
    int hour = Integer.parseInt(parts[0]);
    int minute = Integer.parseInt(parts[1]);
    System.out.println("Hour: " + hour + " Minute: " + minute);

    //done:
    pw.close();
    sc.close();
    s.close();
  }
}
