
// simpletalk CLIENT in java

import java.lang.*;     //pld
import java.net.*;      //pld
import java.io.*;
//import java.io.Externalizable;

public class client {
    static public BufferedReader bin;
    static public int destport = 5431;

    //============================================================

    static public void main(String args[]) {
		bin = new BufferedReader(new InputStreamReader(System.in));
	    String desthost = args[0]; //"ulam.math.luc.edu";
	    if (args.length>=2) {
		destport = (new Integer(args[1])).intValue();
	    }
	    //String desthost = "ulam.math.luc.edu";
	    //String desthost = "localhost";

	    InetAddress dest;
        System.err.print("Looking up address of " + desthost + "...");
	    try {
	        dest = InetAddress.getByName(desthost);
	    }
	    catch (UnknownHostException uhe) {
	        System.err.println("unknown host: " + desthost);
	        return;
	    }
	    System.err.println(" got it!");

	    System.err.println("connecting to port " + destport);
	    Socket s;
	    try {
		s = new Socket(dest, destport);
	    }
	    catch(IOException ioe) {
		System.err.println("no socket available");
	 	return;
	    }

	    OutputStream sout;
	    InputStream sin;

	    try {
	        sout = s.getOutputStream();
	    }
	    catch (IOException ioe) {
	        System.err.println("no socket available");
	        return;
	    }
	    try {
	        sin = s.getInputStream();
	    }
	    catch (IOException ioe) {
	        System.err.println("no socket available");
	        return;
	    }

	    //============================================================

	    // write
		String str = "hellohello";
		byte[] buf = str.getBytes();

	        try {
	            sout.write(buf);
	        }
	        catch (IOException ioe) {
	            System.err.println("write() failed");
	            return;
	        }

		// read 
			int len = 0;
			int bufsize = 512;
			buf = new byte[bufsize];
			try {
				len = sin.read(buf, 0, bufsize);
			}
			catch (IOException ioe) {
				System.err.println("bad read");
				//break;	// probably a socket ABORT; treat as a close
			}
			//if (len == -1) break;
			str = new String(buf, 0, len);
			System.out.println(str);

	    // write
		str = "goodbye";
		buf = str.getBytes();

	        try {
	            sout.write(buf);
	        }
	        catch (IOException ioe) {
	            System.err.println("write() failed");
	            return;
	        }


	    System.err.println("closing");
	    try {
	       s.close();
	   } catch (IOException ioe) {
		   System.err.println("socket close failed");
		   return;
	   }	   /* */
        //winwait();
    }
}

