Skip to content

Commit 4057d17

Browse files
committed
Improve onClose behaviour on client side
TooTallNate#577 Client will delay closing the socket until there was an interrupt which normally terminates the WebsocketWriteThread and causes all remaining message to be pushed out (testsuite fails on random test cases, which is probably caused by a high load and is not representive for a real usage scenario)
1 parent 2ed7d7e commit 4057d17

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

src/main/java/org/java_websocket/client/WebSocketClient.java

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -370,12 +370,6 @@ public final void onWebsocketClose( WebSocket conn, int code, String reason, boo
370370
stopConnectionLostTimer();
371371
if( writeThread != null )
372372
writeThread.interrupt();
373-
try {
374-
if( socket != null )
375-
socket.close();
376-
} catch ( IOException e ) {
377-
onWebsocketError( this, e );
378-
}
379373
onClose( code, reason, remote );
380374
connectLatch.countDown();
381375
closeLatch.countDown();
@@ -464,16 +458,34 @@ private class WebsocketWriteThread implements Runnable {
464458
public void run() {
465459
Thread.currentThread().setName( "WebsocketWriteThread" );
466460
try {
467-
while( !Thread.interrupted() ) {
468-
ByteBuffer buffer = engine.outQueue.take();
469-
ostream.write( buffer.array(), 0, buffer.limit() );
470-
ostream.flush();
461+
try {
462+
while( !Thread.interrupted() ) {
463+
ByteBuffer buffer = engine.outQueue.take();
464+
ostream.write( buffer.array(), 0, buffer.limit() );
465+
ostream.flush();
466+
}
467+
} catch ( InterruptedException e ) {
468+
for (ByteBuffer buffer : engine.outQueue) {
469+
ostream.write( buffer.array(), 0, buffer.limit() );
470+
ostream.flush();
471+
}
471472
}
472473
} catch ( IOException e ) {
473-
handleIOException(e);
474-
} catch ( InterruptedException e ) {
475-
// this thread is regularly terminated via an interrupt
474+
handleIOException( e );
475+
} finally {
476+
closeOutputAndSocket();
477+
}
478+
}
479+
}
480+
481+
private void closeOutputAndSocket() {
482+
try {
483+
if( socket != null ) {
484+
socket.shutdownOutput();
485+
socket.close();
476486
}
487+
} catch ( IOException ex ) {
488+
onWebsocketError( this, ex );
477489
}
478490
}
479491

0 commit comments

Comments
 (0)