import java.nio.channels.*;
import java.net.*;
import javax.net.*;
import javax.net.ssl.*;

public class SSLConnectTest
{

	final static int port = 9876;

	static boolean use_nio = true;

	static class Server extends Thread
	{

		ServerSocket createAndBindServerSocket ( )
			throws Exception
		{
			ServerSocketChannel chan = ServerSocketChannel.open();
			ServerSocket sock = chan.socket();
			sock.bind(new InetSocketAddress("localhost", port));
			return sock;
		}

		public void run ( )
		{
			try
			{
				System.out.println("Server: Creating (non-ssl) server socket");
				ServerSocket sock = createAndBindServerSocket();
				Socket cli = sock.accept();
				System.out.println("Server: Exiting server thread");
			}
			catch (Exception x)
			{
				System.err.println("Exception creating server socket: " + x);
			}
		}
	}

	static class Client
	{

		SSLSocket createConnectAndWrapSSLSocket ( )
			throws Exception
		{
			Socket sock;
			if (use_nio)
			{
				System.out.println("Creating client socket with java.nio");
				SocketChannel chan = SocketChannel.open();
				sock = chan.socket();
			}
			else
			{
				System.out.println("Creating client socket with java.net");
				sock = new Socket();
			}
			System.out.println("Client: about to connect to server socket");
			sock.connect(new InetSocketAddress("localhost", port));
	        String host = sock.getInetAddress().getHostAddress();
	        int portnum = sock.getPort();
	        SSLSocketFactory factory = (SSLSocketFactory)javax.net.ssl.SSLSocketFactory.getDefault();
	        SSLSocket ssl_socket = (SSLSocket) factory.createSocket(sock, host, portnum, false);
			System.out.println("Client: created ssl socket");
	        ssl_socket.setEnabledCipherSuites(ssl_socket.getSupportedCipherSuites());
			System.out.println("Client: setEnabledCipherSuites");
	        ssl_socket.startHandshake();
			System.out.println("Client: handshake complete");
			return ssl_socket;
		}

		public void doit ( )
			throws Exception
		{
			System.out.println("Client: creating client SSL socket");
			SSLSocket sock = createConnectAndWrapSSLSocket();
			System.out.println("Client: exiting client thread");
		}

	}

	public static void main ( String[] args )
		throws Exception
	{
		if (args.length > 0)
			use_nio = false;
		Server serv = new Server();
		Client cli = new Client();
		serv.start();
		Thread.sleep(1000);
		cli.doit();
	}

}

