2424import java .nio .channels .SelectionKey ;
2525import java .nio .channels .Selector ;
2626import java .nio .channels .SocketChannel ;
27+ import java .security .GeneralSecurityException ;
2728
2829import javax .net .ssl .SSLContext ;
2930import javax .net .ssl .SSLEngine ;
@@ -48,30 +49,23 @@ public void setBindAddress(String ipAddress) {
4849 @ Override
4950 protected void init () throws IOException {
5051 _selector = Selector .open ();
51- SocketChannel sch = null ;
52- InetSocketAddress addr = null ;
52+ Task task = null ;
5353
54- try {
55- sch = SocketChannel .open ();
54+ try (SocketChannel sch = SocketChannel .open ()) {
5655 sch .configureBlocking (true );
5756 s_logger .info ("Connecting to " + _host + ":" + _port );
5857
5958 if (_bindAddress != null ) {
6059 s_logger .info ("Binding outbound interface at " + _bindAddress );
6160
62- addr = new InetSocketAddress (_bindAddress , 0 );
63- sch .socket ().bind (addr );
61+ InetSocketAddress bindAddr = new InetSocketAddress (_bindAddress , 0 );
62+ sch .socket ().bind (bindAddr );
6463 }
6564
66- addr = new InetSocketAddress (_host , _port );
67- sch .connect (addr );
68- } catch (IOException e ) {
69- _selector .close ();
70- throw e ;
71- }
65+ InetSocketAddress peerAddr = new InetSocketAddress (_host , _port );
66+ sch .connect (peerAddr );
7267
73- SSLEngine sslEngine = null ;
74- try {
68+ SSLEngine sslEngine = null ;
7569 // Begin SSL handshake in BLOCKING mode
7670 sch .configureBlocking (true );
7771
@@ -82,25 +76,21 @@ protected void init() throws IOException {
8276 Link .doHandshake (sch , sslEngine , true );
8377 s_logger .info ("SSL: Handshake done" );
8478 s_logger .info ("Connected to " + _host + ":" + _port );
85- } catch (Exception e ) {
86- _selector .close ();
87- throw new IOException ("SSL: Fail to init SSL! " + e );
88- }
8979
90- Task task = null ;
91- try {
80+
9281 sch .configureBlocking (false );
93- Link link = new Link (addr , this );
82+ Link link = new Link (peerAddr , this );
9483 link .setSSLEngine (sslEngine );
9584 SelectionKey key = sch .register (_selector , SelectionKey .OP_READ );
9685 link .setKey (key );
9786 key .attach (link );
9887 // Notice we've already connected due to the handshake, so let's get the
9988 // remaining task done
10089 task = _factory .create (Task .Type .CONNECT , link , null );
101- } catch (Exception e ) {
90+ } catch (GeneralSecurityException e ) {
91+ throw new IOException ("Failed to initialise security" , e );
92+ } finally {
10293 _selector .close ();
103- throw new IOException ("Fail to init NioClient! " + e );
10494 }
10595 _executor .execute (task );
10696 }
0 commit comments