88import java .nio .channels .SelectionKey ;
99import java .nio .channels .Selector ;
1010import java .nio .channels .SocketChannel ;
11+ import java .nio .channels .UnresolvedAddressException ;
1112import java .util .Iterator ;
1213import java .util .Set ;
1314
@@ -126,13 +127,17 @@ private void tryToConnect( InetSocketAddress remote ) throws IOException {
126127 client .connect ( remote );
127128 selector = Selector .open ();
128129 client .register ( selector , SelectionKey .OP_CONNECT );
129- conn = new WebSocket ( this , draft , client );
130130 }
131131
132132 // Runnable IMPLEMENTATION /////////////////////////////////////////////////
133133 public void run () {
134134 if (thread == null )
135135 thread = Thread .currentThread ();
136+ interruptableRun ();
137+ thread = null ;
138+ }
139+
140+ protected void interruptableRun () {
136141 try {
137142 tryToConnect ( new InetSocketAddress ( uri .getHost (), getPort () ) );
138143 }
@@ -141,14 +146,17 @@ public void run() {
141146 return ;
142147 }catch ( IOException e ) {//
143148 onError ( conn , e );
144- conn .close ();
145149 return ;
146150 } catch ( SecurityException e ) {
147151 onError ( conn , e );
148- conn .close ();
149152 return ;
153+ } catch ( UnresolvedAddressException e ) {
154+ onError ( conn , e );
155+ return ;
150156 }
151157
158+ conn = new WebSocket ( this , draft , client );
159+
152160 while ( !Thread .interrupted () ) {
153161 SelectionKey key = null ;
154162 try {
@@ -250,6 +258,7 @@ private void sendHandshake() throws IOException , InvalidHandshakeException , In
250258 * @param conn
251259 * @param message
252260 */
261+ @ Override
253262 public void onMessage ( WebSocket conn , String message ) {
254263 onMessage ( message );
255264 }
@@ -259,6 +268,7 @@ public void onMessage( WebSocket conn, String message ) {
259268 *
260269 * @param conn
261270 */
271+ @ Override
262272 public void onOpen ( WebSocket conn ) {
263273 onOpen ();
264274 }
@@ -268,6 +278,7 @@ public void onOpen( WebSocket conn ) {
268278 *
269279 * @param conn
270280 */
281+ @ Override
271282 public void onClose ( WebSocket conn ) {
272283 thread .interrupt ();
273284 onClose ();
@@ -278,7 +289,8 @@ public void onClose( WebSocket conn ) {
278289 *
279290 * @param conn
280291 */
281- public void onError ( WebSocket conn , IOException ex ) {
292+ @ Override
293+ public void onError ( WebSocket conn , Exception ex ) {
282294 onError ( ex );
283295 }
284296
0 commit comments