@@ -114,6 +114,15 @@ public WebSocketClient( URI serverUri , Draft draft , Map<String,String> headers
114114 this .headers = headers ;
115115 this .timeout = connecttimeout ;
116116
117+ try {
118+ channel = SelectorProvider .provider ().openSocketChannel ();
119+ channel .configureBlocking ( true );
120+ conn = (WebSocketImpl ) wf .createWebSocket ( this , draft , channel .socket () );
121+ } catch ( IOException e ) {
122+ onWebsocketError ( null , e );
123+ conn .closeConnection ( CloseFrame .NEVER_CONNECTED , e .getMessage () );
124+ return ;
125+ }
117126 }
118127
119128 /**
@@ -153,7 +162,7 @@ public boolean connectBlocking() throws InterruptedException {
153162 }
154163
155164 public void close () {
156- if ( writethread != null && conn != null ) {
165+ if ( writethread != null ) {
157166 conn .close ( CloseFrame .NORMAL );
158167 }
159168 }
@@ -170,9 +179,7 @@ public void closeBlocking() throws InterruptedException {
170179 * The String to send to the WebSocket server.
171180 */
172181 public void send ( String text ) throws NotYetConnectedException {
173- if ( conn != null ) {
174- conn .send ( text );
175- }
182+ conn .send ( text );
176183 }
177184
178185 /**
@@ -182,14 +189,11 @@ public void send( String text ) throws NotYetConnectedException {
182189 * The Byte-Array of data to send to the WebSocket server.
183190 */
184191 public void send ( byte [] data ) throws NotYetConnectedException {
185- if ( conn != null ) {
186192 conn .send ( data );
187- }
188193 }
189194
190195 private void tryToConnect ( InetSocketAddress remote ) throws IOException , InvalidHandshakeException {
191- channel = SelectorProvider .provider ().openSocketChannel ();
192- channel .configureBlocking ( true );
196+
193197 channel .connect ( remote );
194198
195199 }
@@ -209,7 +213,6 @@ private final void interruptableRun() {
209213 String host = uri .getHost ();
210214 int port = getPort ();
211215 tryToConnect ( new InetSocketAddress ( host , port ) );
212- conn = (WebSocketImpl ) wf .createWebSocket ( this , draft , channel .socket () );
213216 conn .channel = wrappedchannel = wf .wrapChannel ( channel , null , host , port );
214217 timeout = 0 ; // since connect is over
215218 sendHandshake ();
@@ -298,9 +301,6 @@ private void sendHandshake() throws InvalidHandshakeException {
298301 * You can use this method instead of
299302 */
300303 public READYSTATE getReadyState () {
301- if ( conn == null ) {
302- return READYSTATE .NOT_YET_CONNECTED ;
303- }
304304 return conn .getReadyState ();
305305 }
306306
@@ -410,7 +410,7 @@ public void run() {
410410 } catch ( IOException e ) {
411411 conn .eot ();
412412 } catch ( InterruptedException e ) {
413- // this thread is regulary terminated via an interrupt
413+ // this thread is regularly terminated via an interrupt
414414 }
415415 }
416416 }
0 commit comments