void connect ( SocketAddress socketAddress , boolean useSSL ) { ChannelFactory channelFactory = new NioClientSocketChannelFactory ( Executors . newCachedThreadPool ( ) , Executors . newCachedThreadPool ( ) ) ; ChannelPipeline clientPipeline = NettyChannelPipeline . newPipeline ( connection ) ; SslHandler sslHandler = null ; if ( useSSL ) { sslHandler = getClientSSLHandler ( ) ; clientPipeline . addFirst ( "ssl" , sslHandler ) ; } bootstrap = new ClientBootstrap ( channelFactory ) ; bootstrap . setOption ( "tcpNoDelay" , true ) ; bootstrap . setPipeline ( clientPipeline ) ; /* * The connection future and the connection itself aren't perfectly * synchronized so we have to wait for both to acknowledge that the * connection has been made */ final CountDownLatch connectedLatch = new CountDownLatch ( 1 ) ; ConnectionStateListener connectedListener = new ConnectionStateListener ( ) { @ Override public void onConnectionConnected ( ) { connectedLatch . countDown ( ) ; } @ Override public void onConnectionClosing ( ) { } @ Override public void onConnectionClosed ( ) { } } ; connection . addConnectionStateListener ( connectedListener ) ; try { /* Perform connection */ ChannelFuture future = bootstrap . connect ( socketAddress ) ; log . debug ( "connecting" ) ; future . await ( ) ; if ( future . isSuccess ( ) ) { /* This await should be very brief */ connectedLatch . await ( ) ; log . debug ( "connected successfully" ) ; if ( useSSL ) { doSSLHandshake ( sslHandler ) ; } connected = true ; } else { log . debug ( "connection failed" ) ; throw new ConnectionException ( future . getCause ( ) ) ; } } catch ( InterruptedException e ) { throw new ConnectionException ( "Interrupted while connecting" ) ; } finally { connection . removeConnectionStateListener ( connectedListener ) ; } }
Connect to the remote server and perform the SSL handshake if SSL is being used .