Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Netty: Closing WebSockets correctly

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?).

like image 830
Dennis Avatar asked Jan 23 '12 16:01

Dennis


People also ask

How do I close WebSocket connection?

close() The WebSocket. close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED , this method does nothing.

When should I close WebSocket connection?

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.

How long can WebSocket stay open?

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.

What causes WebSocket to close?

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.


2 Answers

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().

like image 124
trustin Avatar answered Oct 16 '22 14:10

trustin


How about

ctx.getChannel().write(new CloseWebSocketFrame()).addListener(ChannelFutureListener.CLOSE);

That should send the CloseWebSocketFrame and then close the channel after that.

like image 24
Vivek Avatar answered Oct 16 '22 15:10

Vivek