user2686299
user2686299

Reputation: 427

Netty. How to share object between handlers?

Yo guys. In my pipeline are 3 handlers:

  1. ConnectionHandler
  2. FrameHandler
  3. PacketHandler

In ConnectionHandler I have created a Session object. I need only 1 Session object for each client, that's why I initialize it in ConnectionHandler, because channelActive method called only 1 time for each client. I wish to pass that Session into PacketHandler. How can I do it?

Upvotes: 3

Views: 2241

Answers (1)

Norman Maurer
Norman Maurer

Reputation: 23567

You can use Channel.attr(...).set(...) and Channel.attr(...).get(...) for this kind of stuff. Check the javadocs.

So something like this:

public static AttibuteKey<String> MY_KEY = AttributeKey.valueOf("MY_KEY");
public final class ConnectHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHanderContext ctx) {
        ctx.channel().attr(MY_KEY).set("Whatever");
    }
}

public final class NextHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String value = ctx.channel().attr(MY_KEY).get();
        // do something
    }
}

Upvotes: 11

Related Questions