Adding an attribute to a Channel before creation

2019-08-27 05:09发布

I'm looking for a way to add an attribute to a Channel before creating it.

The reason is that I need to associate the Channel to some arbitrary object so that I have the ability to get the object from the channel (e.g. in the channelActive() method where I have the Channel and I need the associated object).

The Bootstrap exposes an attr() method but an attribute that would be added this way is available to all channels created from this Bootstrap instance.

Also, adding the attribute after Channel creation is problematic since the channelActive() method may be called before the attribute is added.

标签: java netty
2条回答
混吃等死
2楼-- · 2019-08-27 05:18

Adding via Bootstrap.attr(...) will make the attribute available in channelActive(...) as the attribute is set before fireChannelActive() is called.

If you do not want to use this method you can also just add a ChannelInboundHandler that overrides channelRegistered(...) and add the attribute there by yourself.

查看更多
放荡不羁爱自由
3楼-- · 2019-08-27 05:18

For who needs it, here is a solution:

ChannelFuture registerFuture;
try {
    registerFuture = castBootstrap.register().await();
} catch (InterruptedException e) {
    //Handle the exception
}

final Channel channel = registerFuture.channel();
channel.attr(MY_ATTR_KEY).set(/* some value */);

ChannelFuture connectFuture = channel.connect(/* Resolved socket address */);

Instead of relying on the Bootstrap to create the Channel, the code above creates and registers the Channel, and connects using the Channel interface.

查看更多
登录 后发表回答