@@ -53,7 +53,9 @@ public enum Role {
5353 */
5454 private boolean handshakeComplete = false ;
5555
56- private boolean closeHandshakeComplete = false ;
56+ private boolean closeHandshakeSent = false ;
57+ private boolean connectionClosed = false ;
58+ private boolean isClosePending = false ;
5759 /**
5860 * The listener to notify of WebSocket events.
5961 */
@@ -131,12 +133,12 @@ private void init( WebSocketListener listener, Draft draft, SocketChannel sockch
131133 * When socket related I/O errors occur.
132134 * @throws InterruptedException
133135 */
134- public void handleRead () throws InterruptedException , IOException {
136+ /*package public*/ void handleRead () throws IOException {
135137 if ( !socketBuffer .hasRemaining () ) {
136138 socketBuffer .rewind ();
137139 socketBuffer .limit ( socketBuffer .capacity () );
138140 if ( sockchannel .read ( socketBuffer ) == -1 ) {
139- close ();
141+ close ( CloseFrame . ABNROMAL_CLOSE );
140142 }
141143
142144 socketBuffer .flip ();
@@ -151,7 +153,7 @@ public void handleRead() throws InterruptedException , IOException {
151153
152154 handshakestate = isFlashEdgeCase ( socketBuffer );
153155 if ( handshakestate == HandshakeState .MATCHED ) {
154- channelWrite ( ByteBuffer .wrap ( Charsetfunctions .utf8Bytes ( wsl .getFlashPolicy ( this ) ) ) );
156+ channelWriteDirect ( ByteBuffer .wrap ( Charsetfunctions .utf8Bytes ( wsl .getFlashPolicy ( this ) ) ) );
155157 return ;
156158 }
157159 socketBuffer .mark ();
@@ -166,7 +168,7 @@ public void handleRead() throws InterruptedException , IOException {
166168 handshakestate = d .acceptHandshakeAsServer ( handshake );
167169 if ( handshakestate == HandshakeState .MATCHED ) {
168170 HandshakeBuilder response = wsl .onHandshakeRecievedAsServer ( this , d , handshake );
169- channelWrite ( d .createHandshake ( d .postProcessHandshakeResponseAsServer ( handshake , response ), role ) );
171+ writeDirect ( d .createHandshake ( d .postProcessHandshakeResponseAsServer ( handshake , response ), role ) );
170172 draft = d ;
171173 open ();
172174 handleRead ();
@@ -181,7 +183,7 @@ public void handleRead() throws InterruptedException , IOException {
181183 // go on with an other draft
182184 } catch ( IncompleteHandshakeException e ) {
183185 if ( socketBuffer .limit () == socketBuffer .capacity () ) {
184- abort ( "socketBuffer to small " );
186+ close ( CloseFrame . TOOBIG , "handshake is to big " );
185187 }
186188 // read more bytes for the handshake
187189 socketBuffer .position ( socketBuffer .limit () );
@@ -190,7 +192,7 @@ public void handleRead() throws InterruptedException , IOException {
190192 }
191193 }
192194 if ( draft == null ) {
193- abort ( "no draft matches" );
195+ close ( CloseFrame . PROTOCOL_ERROR , "no draft matches" );
194196 }
195197 return ;
196198 } else {
@@ -202,7 +204,7 @@ public void handleRead() throws InterruptedException , IOException {
202204 open ();
203205 handleRead ();
204206 } else if ( handshakestate != HandshakeState .MATCHING ) {
205- abort ( "the handshake did finaly not match" );
207+ close ( CloseFrame . PROTOCOL_ERROR , "the handshake did finaly not match" );
206208 }
207209 return ;
208210 }
@@ -216,19 +218,19 @@ public void handleRead() throws InterruptedException , IOException {
216218 } else if ( handshakestate == HandshakeState .MATCHING ) {
217219 return ;
218220 } else {
219- abort ( "draft " + draft . getClass (). getSimpleName () + " or server refuses handshake" );
221+ close ( CloseFrame . PROTOCOL_ERROR , "draft " + draft + " refuses handshake" );
220222 }
221223 }
222224 } catch ( InvalidHandshakeException e ) {
223- abort ( "draft " + draft + " refuses handshake: " + e . getMessage () );
225+ close ( e );
224226 }
225227 } else {
226228 // Receiving frames
227229 List <Framedata > frames ;
228230 try {
229231 frames = draft .translateFrame ( socketBuffer );
230232 } catch ( InvalidDataException e1 ) {
231- abort ( /*"detected protocol violations"*/ );
233+ close ( e1 );
232234 return ;
233235 }
234236 for ( Framedata f : frames ) {
@@ -238,8 +240,21 @@ public void handleRead() throws InterruptedException , IOException {
238240 if ( curop == null )// Ignore undefined opcodes
239241 continue ;
240242 else if ( curop == Opcode .CLOSING ) {
241- sendFrame ( new FramedataImpl1 ( f ) );
242- close ();
243+ int code = CloseFrame .NOCODE ;
244+ String reason = "" ;
245+ if ( f instanceof CloseFrame ) {
246+ CloseFrame cf = (CloseFrame ) f ;
247+ code = cf .getCloseCode ();
248+ reason = cf .getMessage ();
249+ }
250+ if ( closeHandshakeSent ) {
251+ // complete the close handshake by disconnecting
252+ closeConnection ( code , reason );
253+ } else {
254+ // echo close handshake
255+ close ( code , reason );
256+ closeConnection ( code , reason );
257+ }
243258 continue ;
244259 } else if ( curop == Opcode .PING ) {
245260 wsl .onPing ( this , f );
@@ -266,10 +281,10 @@ else if( curop == Opcode.CLOSING ) {
266281 currentframe .append ( f );
267282 } catch ( InvalidFrameException e ) {
268283 wsl .onError ( this , e );
269- abort ( "invalid frame: " + e . getMessage () );
284+ close ( e );
270285 }
271286 if ( f .isFin () ) {
272- wsl .onMessage ( this , Charsetfunctions .stingUtf8 ( f .getPayloadData () ) );
287+ wsl .onMessage ( this , Charsetfunctions .stingUtf8 ( currentframe .getPayloadData () ) );
273288 currentframe = null ;
274289 }
275290 }
@@ -279,39 +294,62 @@ else if( curop == Opcode.CLOSING ) {
279294 }
280295
281296 // PUBLIC INSTANCE METHODS /////////////////////////////////////////////////
282- public void abort () {
283- abort ( "" );
297+
298+ /**
299+ * sends the closing handshake.
300+ * may be send in response to an other handshake.
301+ */
302+ public void close ( int code , String message ) {
303+ try {
304+ closeDirect ( code , message );
305+ } catch ( IOException e ) {
306+ closeConnection ( CloseFrame .ABNROMAL_CLOSE );
307+ }
284308 }
285309
286- public void abort ( String problemmessage ) {
287- if ( DEBUG ) {
288- System .out .println ( "Aborting: " + problemmessage );
310+ public void closeDirect ( int code , String message ) throws IOException {
311+ if ( !closeHandshakeSent ) {
312+ closeHandshakeSent = true ;
313+ flush ();
314+ sendFrameDirect ( new CloseFrameBuilder ( code , message ) );
315+ return ;
289316 }
290- close ();
291317 }
318+
292319 /**
293- * Closes the underlying SocketChannel, and calls the listener's onClose
294- * event handler.
295- */
296- public void close () {
297- if ( closeHandshakeComplete ) {
320+ * closes the socket no matter if the closing handshake completed.
321+ * Does not send any not yet written data before closing.
322+ * Calling this method twice will have no effect.
323+ **/
324+ public void closeConnection ( int code , String message ) {
325+ if ( connectionClosed ) {
298326 return ;
299327 }
300- // TODO Send error/closecode here in some cases
301- closeHandshakeComplete = true ;
328+ connectionClosed = true ;
302329 try {
303- handleWrite ();
304330 sockchannel .close ();
305331 } catch ( IOException e ) {
306- e . printStackTrace ( );
332+ wsl . onError ( this , e );
307333 }
308- this .wsl .onClose ( this );
334+ this .wsl .onClose ( this , code , message );
309335 if ( draft != null )
310336 draft .reset ();
311337 currentframe = null ;
312338 handshakerequest = null ;
313339 }
314340
341+ public void closeConnection ( int code ) {
342+ closeConnection ( code , "" );
343+ }
344+
345+ public void close ( int code ) {
346+ close ( code , "" );
347+ }
348+
349+ public void close ( InvalidDataException e ) {
350+ close ( e .getCloseCode (), e .getMessage () );
351+ }
352+
315353 /**
316354 * @return True if all of the text was sent to the client by this thread or the given data is empty
317355 * False if some of the text had to be buffered to be sent later.
@@ -345,6 +383,12 @@ public void sendFrame( Framedata framedata ) throws InterruptedException {
345383 channelWrite ( draft .createBinaryFrame ( framedata ) );
346384 }
347385
386+ private void sendFrameDirect ( Framedata framedata ) throws IOException {
387+ if ( DEBUG )
388+ System .out .println ( "send frame: " + framedata );
389+ channelWriteDirect ( draft .createBinaryFrame ( framedata ) );
390+ }
391+
348392 boolean hasBufferedData () {
349393 return !this .bufferQueue .isEmpty ();
350394 }
@@ -353,7 +397,7 @@ boolean hasBufferedData() {
353397 * @return True if all data has been sent to the client, false if there
354398 * is still some buffered.
355399 */
356- public void handleWrite () throws IOException {
400+ public void flush () throws IOException {
357401 ByteBuffer buffer = this .bufferQueue .peek ();
358402 while ( buffer != null ) {
359403 sockchannel .write ( buffer );
@@ -400,7 +444,17 @@ private void channelWrite( List<ByteBuffer> bufs ) throws InterruptedException {
400444 }
401445 }
402446
403- private void open () throws InterruptedException , IOException {
447+ private void channelWriteDirect ( ByteBuffer buf ) throws IOException {
448+ while ( buf .hasRemaining () )
449+ sockchannel .write ( buf );
450+ }
451+ private void writeDirect ( List <ByteBuffer > bufs ) throws IOException {
452+ for ( ByteBuffer b : bufs ) {
453+ channelWriteDirect ( b );
454+ }
455+ }
456+
457+ private void open () throws IOException {
404458 if ( DEBUG )
405459 System .out .println ( "open using draft: " + draft .getClass ().getSimpleName () );
406460 handshakeComplete = true ;
@@ -415,6 +469,10 @@ public InetSocketAddress getLocalSocketAddress() {
415469 return (InetSocketAddress ) sockchannel .socket ().getLocalSocketAddress ();
416470 }
417471
472+ public boolean isClosed () {
473+ return connectionClosed ;
474+ }
475+
418476 @ Override
419477 public String toString () {
420478 return super .toString (); // its nice to be able to set breakpoints here
0 commit comments