May I upstream self-created messages?

brunodecarvalho kindernade at gmail.com
Tue Aug 24 11:01:29 EDT 2010


There's two ways to accomplish what you need.

First one is sending an implementation of ChannelEvent upstream, as you've
mentioned. In this approach you'll have to override the method
handleUpstream() in your final ChannelHandler to include the logic to deal
with your ChannelEvent instance, something like:

public class YourEvent extends ChannelEvent {
    ...
}

public class YourHandler extends SimpleChannelUpstreamHandler {

    @Override
    public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)
            throws Exception {
        if (e instanceof YourEvent) {
            // handle YourEvent
        } else {
            super.handleUpstream(ctx, e);
        }

        ...
}

The other option is having a ByteCounter per pipeline and linking both your
ByteCounter and the final handler. Something like:

ChannelPipelineFactory pf = new ChannelPipelineFactory() {

    @Override
    public ChannelPipeline getPipeline() throws Exception {
        // create counter and handler, link both and return
        // them in the same pipeline
        ByteCounter counter = new ByteCounter();
        YourHandler handler = new YourHandler(counter);
        return Channels.pipeline(counter, ..., handler);
    }
}

This latter approach is probably better if you need to query the number of
transferred bytes at any given time, rather than just upon disconnection.

As a side note, if you're creating ByteCounter instances per pipeline, I'd
avoid using the get/setAttachment and would stick to instance variables -
leave the attachment for those cases where you just can't avoid it. If two
of the handlers in the pipeline mess around with the context attachment,
your app will likely go boom.

Also, AtomicInteger would be a better choice than Integer for a counter ;)


Cheers,
  Bruno
-- 
View this message in context: http://netty-forums-and-mailing-lists.685743.n2.nabble.com/May-I-upstream-self-created-messages-tp5457151p5457236.html
Sent from the Netty User Group mailing list archive at Nabble.com.


More information about the netty-users mailing list