Netty Different Pipeline Per UDP Datagram

前端 未结 2 905
一个人的身影
一个人的身影 2021-02-06 19:16

We\'ve got a server which is already implemented in TCP/IP but we now have a requirement for the protocol to support UDP as well.

Each UDP datagram sent contains everyth

相关标签:
2条回答
  • 2021-02-06 19:46

    I'm not sure about how the UDP channels are handled, but if the channels are distinct per datagram, you could store your state in ChannelLocals.

    0 讨论(0)
  • 2021-02-06 19:55

    Like I said in IRC, I think that could do what you want or at least give you some idea.

    public class Example {
    
        public static void main(String[] args) {
            final ChannelPipelineHandlerImpl perDatagramFactory = new ChannelPipelineHandlerImpl();
    
            DatagramChannelFactory udpFactory = new NioDatagramChannelFactory(Executors.newCachedThreadPool());
    
            ConnectionlessBootstrap udpBootstrap = new ConnectionlessBootstrap(udpFactory);
    
            udpBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    
                public ChannelPipeline getPipeline() throws Exception {
                    return Channels.pipeline(new DistinctChannelPipelineHandler(perDatagramFactory));
                }
            });
    
        }
    
        private static final class DistinctChannelPipelineHandler implements ChannelDownstreamHandler, ChannelUpstreamHandler {
            private ChannelPipelineFactory factory;
    
            public DistinctChannelPipelineHandler(ChannelPipelineFactory factory) {
                this.factory = factory;
            }
    
            public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
                ChannelPipeline pipeline = factory.getPipeline();
                pipeline.attach(ctx.getChannel(), ctx.getPipeline().getSink());
                pipeline.sendUpstream(e);
    
                ctx.sendUpstream(e);
    
            }
    
            public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
                ChannelPipeline pipeline = factory.getPipeline();
                pipeline.attach(ctx.getChannel(), ctx.getPipeline().getSink());
                pipeline.sendDownstream(e);
    
                ctx.sendDownstream(e);
            }
    
        }
    
        private static final class ChannelPipelineHandlerImpl implements ChannelPipelineFactory {
    
            public ChannelPipeline getPipeline() throws Exception {
                // Add your handlers here
                return Channels.pipeline();
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题