/*
 * CnxDateClient.java
 *
 * Copyright (c) 2008 Luis Rei <luis.rei@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */
import java.io.*;
import java.net.*;

public class CnxDateClient {

	public static void main(String[] args) throws Exception {
		Socket sock = null;
		OutputStream out = null;
		BufferedReader in = null;
		Integer port = null;
		
		if (args.length != 2) {
			System.out.println("Usage: CnxDateClient [host] [port]");
			System.exit(0);
		}
		
		port = new Integer(args[1]);

		try {
			sock = new Socket(args[0], port);
			out = sock.getOutputStream();
			in = new BufferedReader(
					new InputStreamReader(sock.getInputStream()));
		} catch (UnknownHostException e) {
			System.err.println("unknown host " + args[0]);
			System.exit(0);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for the connection");
			System.exit(0);
		}
		
		byte[] mbuf = null;
		char[] cbuf = new char[2048];
		String reply;
		while (true) {
			for (int ii = 0; ii < 3; ii++) {
				// Send DATE
				String msg = new String("DATE");
				mbuf = msg.getBytes();
				out.write(mbuf);
				System.out.println("Client Sent (to " + args[0]
				                    +"): " + msg);
				
				// Read the reply
				in.read(cbuf, 0, 2048);
				reply = new String(cbuf);
				System.out.println("Client Received: "
						+ reply);
				Thread.sleep(1000); // sleep 1 sec
			}
			// Send ADJTIME
			String msg = new String("ADJTIME 5");
			mbuf = msg.getBytes();
			out.write(mbuf);
			System.out.println("Client Sent (to " + args[0]
			                    +"): " + msg);
			// Read the reply
			in.read(cbuf, 0, 2048);
			reply = new String(cbuf);
			System.out.println("Client Received: "
					+ reply);
			Thread.sleep(1000);
		}
		
		//out.close();
		//in.close();
		//sock.close();
	}
}

