Example usage for io.netty.handler.codec LengthFieldBasedFrameDecoder LengthFieldBasedFrameDecoder

List of usage examples for io.netty.handler.codec LengthFieldBasedFrameDecoder LengthFieldBasedFrameDecoder

Introduction

In this page you can find the example usage for io.netty.handler.codec LengthFieldBasedFrameDecoder LengthFieldBasedFrameDecoder.

Prototype

public LengthFieldBasedFrameDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,
        int lengthAdjustment, int initialBytesToStrip) 

Source Link

Document

Creates a new instance.

Usage

From source file:alluxio.network.protocol.RPCMessage.java

License:Apache License

/**
 * Creates a decoder that splits up the incoming ByteBuf into new ByteBuf's according to a length
 * field in the input.//w w  w .j  a  va 2s .co m
 *
 * The encoding scheme is: [(long) frame length][message payload]
 * The frame length is NOT included in the output ByteBuf.
 *
 * @return the frame decoder for Netty
 */
public static ByteToMessageDecoder createFrameDecoder() {
    // maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip
    return new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, Longs.BYTES, -Longs.BYTES, Longs.BYTES);
}

From source file:blazingcache.network.netty.NettyChannelAcceptor.java

License:Apache License

public void start() throws Exception {
    if (ssl) {//  w  w  w .  j a v a2  s  .  c o m
        if (sslCertFile == null) {
            LOGGER.log(Level.SEVERE, "start SSL with self-signed auto-generated certificate");
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            try {
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).ciphers(sslCiphers)
                        .build();
            } finally {
                ssc.delete();
            }
        } else {
            LOGGER.log(Level.SEVERE, "start SSL with certificate " + sslCertFile.getAbsolutePath()
                    + " chain file " + sslCertChainFile.getAbsolutePath());
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            sslCtx = SslContextBuilder.forServer(sslCertChainFile, sslCertFile, sslCertPassword)
                    .ciphers(sslCiphers).build();
        }

    }
    if (callbackThreads == 0) {
        callbackExecutor = Executors.newCachedThreadPool();
    } else {
        callbackExecutor = Executors.newFixedThreadPool(callbackThreads, new ThreadFactory() {
            private final AtomicLong count = new AtomicLong();

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "blazingcache-callbacks-" + count.incrementAndGet());
            }
        });
    }
    bossGroup = new NioEventLoopGroup(workerThreads);
    workerGroup = new NioEventLoopGroup(workerThreads);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    NettyChannel session = new NettyChannel("unnamed", ch, callbackExecutor, null);
                    if (acceptor != null) {
                        acceptor.createConnection(session);
                    }

                    //                        ch.pipeline().addLast(new LoggingHandler());
                    // Add SSL handler first to encrypt and decrypt everything.
                    if (ssl) {
                        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
                    }

                    ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                    ch.pipeline().addLast("lengthbaseddecoder",
                            new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    //
                    ch.pipeline().addLast("messageencoder", new DataMessageEncoder());
                    ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
                    ch.pipeline().addLast(new InboundMessageHandler(session));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f = b.bind(host, port).sync(); // (7)
    this.channel = f.channel();

}

From source file:blazingcache.network.netty.NettyConnector.java

License:Apache License

public NettyChannel connect() throws Exception {
    if (ssl) {//from w w w.jav  a 2  s. c  om
        this.sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    }
    group = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    channel = new NettyChannel(host + ":" + port, ch, callbackExecutor, NettyConnector.this);
                    channel.setMessagesReceiver(receiver);
                    if (ssl) {
                        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));
                    }
                    if (socketTimeout > 0) {
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(socketTimeout));
                    }
                    ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                    ch.pipeline().addLast("lengthbaseddecoder",
                            new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    //
                    ch.pipeline().addLast("messageencoder", new DataMessageEncoder());
                    ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
                    ch.pipeline().addLast(new InboundMessageHandler(channel));
                }
            });

    ChannelFuture f = b.connect(host, port).sync();
    socketchannel = f.channel();
    return channel;

}

From source file:com.emin.igwmp.skm.core.netty.handler.SocksServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
    // AMF3 ??/*  w  ww .j  ava2s.c o  m*/
    //pipeline.addLast("decoder", new DecoderAMF3());
    //pipeline.addLast("encoder", new EncoderAMF3());

    // ?object?? ?Java Object
    //pipeline.addLast("objectEncoder", new ObjectEncoder());
    //pipeline.addLast("objectDecoder", new ObjectDecoder(ClassResolvers.cacheDisabled(null)));

    // UTF-8??? ? ?
    pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
    pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
    pipeline.addLast("ping", new IdleStateHandler(5, 5, 10));
    // // 20s20s 30s
    pipeline.addLast("handler", socksServerHandler);
    //        ch.pipeline().addLast(
    //                new LoggingHandler(LogLevel.DEBUG),
    //                new SocksPortUnificationServerHandler(),
}

From source file:com.github.brandtg.switchboard.LogReceiver.java

License:Apache License

/**
 * A server that listens for log regions and pipes them to an output stream.
 *
 * @param address/*from w  w  w  .j  a va 2  s  .  co  m*/
 *  The socket address on which to listen
 * @param eventExecutors
 *  The Netty executor service to use for incoming traffic
 * @param outputStream
 *  The output stream to which all data should be piped
 */
public LogReceiver(InetSocketAddress address, EventLoopGroup eventExecutors, final OutputStream outputStream) {
    this.address = address;
    this.isShutdown = new AtomicBoolean(true);
    this.listeners = new HashSet<Object>();
    this.serverBootstrap = new ServerBootstrap().group(eventExecutors).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline()
                            .addLast(new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET,
                                    LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP));
                    ch.pipeline().addLast(new LogMessageHandler(outputStream, listeners));
                }
            });
}

From source file:com.github.kpavlov.jreactive8583.netty.pipeline.Iso8583ChannelInitializer.java

License:Apache License

@Override
public void initChannel(C ch) throws Exception {
    final ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast("lengthFieldFameDecoder", new LengthFieldBasedFrameDecoder(
            configuration.getMaxFrameLength(), 0, headerLength, 0, headerLength));
    pipeline.addLast("iso8583Decoder", createIso8583Decoder(isoMessageFactory));

    pipeline.addLast("iso8583Encoder", isoMessageEncoder);

    if (configuration.addLoggingHandler()) {
        pipeline.addLast(workerGroup, "logging", loggingHandler);
    }//from w  w w. java  2s.  com

    if (configuration.replyOnError()) {
        pipeline.addLast(workerGroup, "replyOnError", loggingHandler);
    }

    pipeline.addLast("idleState", new IdleStateHandler(0, 0, configuration.getIdleTimeout()));
    pipeline.addLast("idleEventHandler", new IdleEventHandler(isoMessageFactory));
    if (customChannelHandlers != null) {
        pipeline.addLast(workerGroup, customChannelHandlers);
    }

    if (configurer != null) {
        configurer.configurePipeline(pipeline, configuration);
    }
}

From source file:com.github.milenkovicm.kafka.connection.ControlKafkaBroker.java

License:Apache License

@Override
protected ChannelInitializer<SocketChannel> pipeline() {
    return new ChannelInitializer<SocketChannel>() {
        @Override//  w  w  w. j  a v a 2 s . c  om
        public void initChannel(SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new LengthFieldBasedFrameDecoder(Short.MAX_VALUE, 0, 4, 0, 4));
            if (properties.get(ProducerProperties.NETTY_DEBUG_PIPELINE)) {
                pipeline.addLast(new LoggingHandler());
            }
            pipeline.addLast(new MetadataHandler(properties));
            pipeline.addLast(new TerminalHandler());
        }
    };
}

From source file:com.github.milenkovicm.kafka.connection.DataKafkaBroker.java

License:Apache License

@Override
protected ChannelInitializer<SocketChannel> pipeline() {
    return new ChannelInitializer<SocketChannel>() {
        @Override/* w ww. j a va 2  s .  com*/
        public void initChannel(SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new LengthFieldBasedFrameDecoder(Short.MAX_VALUE, 0, 4, 0, 4));
            pipeline.addLast(metricHandler);

            if (properties.get(ProducerProperties.NETTY_DEBUG_PIPELINE)) {
                pipeline.addLast(new LoggingHandler());
            }

            if (properties.get(ProducerProperties.NETTY_HANDLER_COMPOSITE)) {
                pipeline.addLast(new CompositeProducerHandler(topicName, properties));
            } else {
                pipeline.addLast(new CopyProducerHandler(topicName, properties));
            }
            pipeline.addLast(new TerminalHandler());
        }
    };
}

From source file:com.github.mrstampy.gameboot.otp.netty.client.ClearClientInitializer.java

License:Open Source License

@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new LengthFieldPrepender(4));
    pipeline.addLast(new ObjectEncoder());
    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
    pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
    pipeline.addLast(clientHandler);/*  w  ww. jav a2  s  .  com*/
}

From source file:com.github.mrstampy.gameboot.otp.netty.client.EncryptedClientInitializer.java

License:Open Source License

@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new SslHandler(createSslEngine()));
    pipeline.addLast(new LengthFieldPrepender(2));
    pipeline.addLast(new ObjectEncoder());
    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2));
    pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
    pipeline.addLast(clientHandler);/*  ww w .jav  a 2 s .co m*/
}