0
votes

I want to refactor an old Netty 3.x websocket server to the new version 4.0. I need to send a "welcome message" to the client, as soon the Websocket handshake is finished. Maybe someone can give me hint, how I can get informed as soon the websocket connection is ready to use? I am playing around with the websocket server example.

2

2 Answers

3
votes

WebSocketServerHandshaker.handshake() returns a ChannelFuture that gets notified when handshake is completed.

0
votes

If Websocket handshake is done, Netty will raise an user event.

See https://github.com/netty/netty/blob/netty-4.1.51.Final/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandshakeHandler.java#L101

The UserEvent in Netty 4.0 is WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE, in Netty 4.1 is WebSocketServerProtocolHandler.HandshakeComplete.

You can override userEventTriggered method in your WebSocketHandler:

public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (frame instanceof TextWebSocketFrame) {
            // Send the uppercase string back.
            String request = ((TextWebSocketFrame) frame).text();
            ctx.channel().writeAndFlush(new TextWebSocketFrame(request.toUpperCase()));
        } else {
            String message = "unsupported frame type: " + frame.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            WebSocketServerProtocolHandler.HandshakeComplete complete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
            System.out.println("New WebSocket handshake complete, uri:" + complete.requestUri());
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}