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

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

Introduction

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

Prototype

public LengthFieldPrepender(int lengthFieldLength) 

Source Link

Document

Creates a new instance.

Usage

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

License:Apache License

public void start() throws Exception {
    if (ssl) {//from w w w .  j  a v  a 2  s  .  co 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 ww .j  a v  a2s.  c o  m
        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  w  w .jav  a2 s .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.LogRegionResource.java

License:Apache License

/**
 * Creates a resource that can serve log regions.
 *
 * @param eventExecutors The Netty executors used to send log regions asynchronously
 * @param logIndex       Used to determine which file regions to send
 * @param logReader      Used to physically read file regions if async is not used
 *///from   ww  w .  j  a va  2s .  c  o m
public LogRegionResource(EventLoopGroup eventExecutors, LogIndex logIndex, LogReader logReader) {
    this.logIndex = logIndex;
    this.logReader = logReader;
    this.bootstrap = new Bootstrap().group(eventExecutors).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new LengthFieldPrepender(4));
                    channel.pipeline().addLast(new ChunkedWriteHandler());
                }
            });
}

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. j a  v a  2 s.c  o m*/
}

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);//from  ww w .j  av  a  2 s .c  o m
}

From source file:com.github.mrstampy.gameboot.otp.netty.server.ClearServerInitializer.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(utils.getBean(OtpClearNettyHandler.class));
}

From source file:com.github.mrstampy.gameboot.otp.netty.server.EncryptedServerInitializer.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(utils.getBean(OtpEncryptedNettyHandler.class));
}

From source file:com.github.zk1931.jzab.transport.NettyTransport.java

License:Apache License

/**
 * Constructs a NettyTransport object.//w ww . java2  s .com
 *
 * @param hostPort "hostname:port" string. The netty transport binds to the
 *                 port specified in the string.
 * @param receiver receiver callback.
 * @param sslParam Ssl parameters.
 * @param dir the directory used to store the received file.
 */
public NettyTransport(String hostPort, final Receiver receiver, SslParameters sslParam, final File dir)
        throws InterruptedException, GeneralSecurityException, IOException {
    super(receiver);
    this.keyStore = sslParam.getKeyStore();
    this.trustStore = sslParam.getTrustStore();
    this.keyStorePassword = sslParam.getKeyStorePassword() != null
            ? sslParam.getKeyStorePassword().toCharArray()
            : null;
    this.trustStorePassword = sslParam.getTrustStorePassword() != null
            ? sslParam.getTrustStorePassword().toCharArray()
            : null;
    this.dir = dir;
    if (isSslEnabled()) {
        initSsl();
    }

    this.hostPort = hostPort;
    String[] address = hostPort.split(":", 2);
    int port = Integer.parseInt(address[1]);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (isSslEnabled()) {
                        SSLEngine engine = serverContext.createSSLEngine();
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(true);
                        ch.pipeline().addLast(new SslHandler(engine));
                    }
                    // Incoming handlers
                    ch.pipeline().addLast(new MainHandler());
                    ch.pipeline().addLast(new ServerHandshakeHandler());
                    ch.pipeline().addLast(new NotifyHandler());
                    ch.pipeline().addLast(new ErrorHandler());
                    // Outgoing handlers.
                    ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
                }
            });

    // Travis build fails once in a while because it fails to bind to a port.
    // This is most likely a transient failure. Retry binding for 5 times with
    // 1 second sleep in between before giving up.
    int bindRetryCount = 5;
    for (int i = 0;; i++) {
        try {
            channel = b.bind(port).sync().channel();
            LOG.info("Server started: {}", hostPort);
            return;
        } catch (Exception ex) {
            if (i >= bindRetryCount) {
                throw ex;
            }
            LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort);
            Thread.sleep(1000);
        }
    }
}

From source file:com.kixeye.kixmpp.p2p.node.NodeClient.java

License:Apache License

public void initialize(final String host, int port, final EventLoopGroup workerGroup,
        final MessageRegistry messageRegistry, final ChannelInboundHandlerAdapter channelListener)
        throws InterruptedException {
    // prepare connection
    Bootstrap boot = new Bootstrap();
    boot.group(workerGroup);//  www . j ava2 s.c om
    boot.channel(NioSocketChannel.class);
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();

            //p.addLast(new LoggingHandler());

            // encoders
            p.addLast(new LengthFieldPrepender(4));
            p.addLast(new ProtostuffEncoder(messageRegistry));

            // decoders
            p.addLast(new LengthFieldBasedFrameDecoder(0x100000, 0, 4, 0, 4));
            p.addLast(new ProtostuffDecoder(messageRegistry));
            p.addLast(channelListener);
        }
    });

    // connect
    channel = boot.connect(host, port).sync().channel();
}