Dennis
Dennis

Reputation: 4177

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

Upvotes: 5

Views: 6287

Answers (4)

buptfb
buptfb

Reputation: 1

I encountered the same problem(close a WebSocket channel/connection from server side ), which was solved in this way:

ctx.getChannel().writeAndFlush(new CloseWebSocketFrame(1000, "Server closed connection."));

Upvotes: 0

Vivek
Vivek

Reputation: 89

How about

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

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

Upvotes: 2

trustin
trustin

Reputation: 12351

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

Upvotes: 6

Norman Maurer
Norman Maurer

Reputation: 23557

What version are you using ?

Have you tried todo this:

ctx.getChannel().write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);

?

Upvotes: 0

Related Questions