简体   繁体   中英

How attach an object to a channel before handlers receive events with Netty?

I have a synchronization issue regarding a bind request and a upstream handler that receives a channelBound event. I need to attach an object to the channel before the handler can ever receive the channelBound event due to the fact that the handler needs to use the object to handle the callback. Example below.

Handler example:

public class MyClientHandler extends SimpleChannelUpstreamHandler {

    @Override
    public void channelBound(ChannelHandlerContext ctx, ChannelStateEvent e) {

        /* Problem: This can occur while the channel attachment is still null. */
        MyStatefulObject obj = e.getChannel().getAttachment();

        /* Do important things with attachment. */ 
    }

}

Main example:

ClientBootstrap bootstrap = ... //Assume this has been configured correctly.

ChannelFuture f = bootstrap.bind(new InetSocketAddress("192.168.0.15", 0));

/* It is possible the boundEvent has already been fired upstream
 *  by the IO thread when I get here. 
 */
f.getChannel().setAttachment(new MyStatefulObject());

Possible Soultions

I've come up with a couple of solutions to get around this but they both kind of "smell" which is why I'm here asking if anyone has a clean way of doing this.

Solution 1: Spin or block in the channelBound callback until the attachment is not null. I don't like this solution because it ties up an I/O worker.

Solution 2: Make MyClientHandler in to a bi-directional handler and get the attachment using a ThreadLocal in a bindRequested downstream callback. I don't like this because it relies on a Netty implementation detail that the requesting thread is used to fire the bindRequested event.

I find solution 1 to be more tolerable than solution 2. So if that is what I need to do I will.

Is there an easy way to get a channel reference without requesting a bind or connect first?

Make your ChannelPipelineFactory implementation accept a constructor parameter and specify the attachment there. Place a handler in front of all other handlers and make the first handler's channelOpen() method sets the attachment, and then remove the first handler from the pipeline, because it's not needed anymore.

Yes it is possible that, boundEvent can get the handler before you set the attachment to the channel.

If the attachment is very specific to every channel your opening, then you can register a channel future listener on bind future and set the attachment on operationComplete() by setting up everything without using BootStraps. Following is a modified version of EchoClient Example, It works fine.

       // Configure the client.
    final NioClientSocketChannelFactory clientSocketChannelFactory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool());


    // Set up the pipeline factory.
    final ChannelPipelineFactory channelPipelineFactory = new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(
                    new MyClientHandler());
        }
    };

    ChannelPipeline pipeline = channelPipelineFactory.getPipeline();
    final Channel channel = clientSocketChannelFactory.newChannel(pipeline);

    channel.getConfig().setPipelineFactory(channelPipelineFactory);
    channel.getConfig().setOption("tcpNoDelay", true);
    channel.getConfig().setOption("receiveBufferSize", 1048576);
    channel.getConfig().setOption("sendBufferSize", 1048576);

    ChannelFuture boundFuture = Channels.future(channel);

    boundFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.getChannel().setAttachment(new Object());// set the channel attachment
            }
        }
    });


    channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent(channel, boundFuture, ChannelState.BOUND, new InetSocketAddress(host, 0)));

    ChannelFuture connectFuture = Channels.future(channel); 
    channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent(channel, connectFuture, ChannelState.CONNECTED, new InetSocketAddress(host, port)));

    channel.getCloseFuture().awaitUninterruptibly();

    clientSocketChannelFactory.releaseExternalResources();// do not forget to do this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM