Netty 4.0:检测,如果Websocket握手完成

时间:2013-09-08 17:39:43

标签: java websocket netty

我想将旧的Netty 3.x websocket服务器重构为新版本4.0。 Websocket握手完成后,我需要向客户端发送“欢迎消息”。也许有人可以给我提示,如果websocket连接准备就绪,我怎么能得到通知?我正在玩websocket server example

2 个答案:

答案 0 :(得分:2)

WebSocketServerHandshaker.handshake()返回一个ChannelFuture,在握手完成后会收到通知。

答案 1 :(得分:0)

如果完成了Websocket握手,Netty将引发一个用户事件。

请参见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

在Netty 4.0中,UserEvent为WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE,在Netty 4.1中为WebSocketServerProtocolHandler.HandshakeComplete

您可以在WebSocketHandler中覆盖userEventTriggered方法:

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);
        }
    }
}