在netty websockets中通过ChannelHandlerContext标识用户

时间:2017-06-29 19:43:56

标签: java websocket netty

我无法弄清楚如何识别用户,因为ChannelHandlerContext在LoggingHandler和SimpleChannelInboundHandler中不一样:

onClick

LoggingHandler:

class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
    public void initChannel(SocketChannel ch) throws Exception {                

            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast(new HttpServerCodec());
            pipeline.addLast(new HttpObjectAggregator(65536));
            pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
            pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH));
            pipeline.addLast(new WebSocketFrameHandler());
            pipeline.addLast(new SessionManagerAxx());   

    }
}

FrameHandler:

class SessionManagerAxx extends LoggingHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

            if (evt.equals(ServerHandshakeStateEvent.HANDSHAKE_COMPLETE)) {
                   ///add the user
                    Clients.getInstance().addNewClient(ctx);
            }

            super.userEventTriggered(ctx, evt);
    }
}

3 个答案:

答案 0 :(得分:0)

您可以向Channel.attr(...)添加一些内容,然后在两个处理程序中使用。

答案 1 :(得分:0)

身份验证在&#34;状态管理&#34; ChannelHandler javadoc

的部分

答案 2 :(得分:0)

管道中的节点似乎不共享ChannelHandlerContext 所以我解决了在单个类中加入FrameHandler和SessionManager的问题。