Tomasz Kryński
Tomasz Kryński

Reputation: 541

Netty websocket close gracefully

I need to make my websocket to close gracefully. Firstly send all messages that are waiting in buffer then close.

channel.flush();
channel.close();

seems not right, because I dont have any completion handler for flush method to do close after it is done.

Is there any way to do this. Netty used: 4.1.0.Beta3

Upvotes: 0

Views: 513

Answers (1)

Chris O'Toole
Chris O'Toole

Reputation: 1281

The trick you can use is to writeAndFlush an empty buffer, then attach a listener to that call. Unpooled.EMPTY_BUFFER can make this pretty easy.

channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(...
    channel.close();
)};

If all you want to do is close the channel after the flush then you can use ChannelFutureListener.CLOSE to simplify your code.

channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);

If you do this often enough, then you may want to write a static helper method like the Netty examples do.

Upvotes: 2

Related Questions