How can I close a WebSocket channel/connection from server side correctly? If I use a ctx.getChannel().close()
, the onerror
in the Brwoser (Firefox 9) is thrown:
The connection to ws://localhost:8080/websocket was interrupted while the page was loading
I also tried to send a CloseWebSocketFrame
within the channelClosed
-method in the WebSocketServerHandler
:
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
CloseWebSocketFrame close = new CloseWebSocketFrame();
ctx.getChannel().write(close);
}
This throws an ClosedChannelException
(maybe related to this?).
close() The WebSocket. close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED , this method does nothing.
If you are writing a server, you should make sure to send a close frame when the server closes a client connection. The normal TCP socket close method can sometimes be slow and cause applications to think the connection is still open even when it's not.
A WebSocket connection can in theory last forever. Assuming the endpoints remain up, one common reason why long-lived TCP connections eventually terminate is inactivity.
It looks like this is the case when Chrome is not compliant with WebSocket standard. When the server initiates close and sends close frame to a client, Chrome considers this to be an error and reports it to JS side with code 1006 and no reason message.
You have to do this:
ch.write(new CloseWebSocketFrame());
then the server will close the connection. If the connection is not closed soon enough, you can call ch.close()
.
How about
ctx.getChannel().write(new CloseWebSocketFrame()).addListener(ChannelFutureListener.CLOSE);
That should send the CloseWebSocketFrame and then close the channel after that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With