import java.net.*;
import java.io.*;
import javax.net.ssl.*;


public class TCPSecureClientNoAuth {
    private static final int DEFAULT_SIZE = 1024;

    public static void main(String[] args) throws Exception {
 
        // Processing the command line arguments
        if (args.length < 3) {
            System.err.println("Too few arguments...need 3");
            System.err.println("USAGE: java TCPSecureClientNoAuth host port msg");
            System.exit(-1);
        }
        String serverName = args[0];
        String msg = args[2];
        int portNumber = -1;
        try {
            portNumber = Integer.parseInt(args[1]);
        } catch (IllegalArgumentException e) {
             System.err.println("Error converting port number " + portNumber);
             System.err.println("USAGE: java TCPSecureClientNoAuth host port msg");
             System.exit(-1);
        }

        // Setting up the secure socket with no client authentication
        SSLSocket socket = null;
	try {
	    SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault();
	    socket = (SSLSocket)factory.createSocket(serverName, portNumber);
	    socket.startHandshake();   // Isn't necessary depending on how data is written
        } catch (Exception e) {
            System.err.println("Failed to set up unauthenticated SSL on port " + portNumber
                                + " to server " + serverName); 
            e.printStackTrace();
            System.exit(-1); 
        }

        // Sending a message on the secure socket and reading a reply
        try {
           DataOutputStream out = new DataOutputStream(socket.getOutputStream());
           String sendingString = "Sending:" + msg; 
           out.write(sendingString.getBytes());
           out.flush();
           DataInputStream in = new DataInputStream(socket.getInputStream());
           byte [] buf = new byte[DEFAULT_SIZE];
           int bytesRead = in.read(buf);  // no guarantee here we have all, just some
           if (bytesRead > 0)
               System.out.println("Received: {" + new String(buf, 0, bytesRead) + "}");
           else
               System.out.println("Warning...did not receive any bytes");
         } catch (Exception e) {
            System.err.println("Error in sending or receiving the data...");
            e.printStackTrace();
            System.exit(-1);
         }
    }
}

