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:com.yahoo.pulsar.client.api.MockBrokerService.java

License:Apache License

public void startMockBrokerService() throws Exception {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("mock-pulsar-%s").build();
    final int numThreads = 2;

    final int MaxMessageSize = 5 * 1024 * 1024;
    EventLoopGroup eventLoopGroup;/*from  w  w  w . j  av a  2 s .  c  o  m*/

    try {
        if (SystemUtils.IS_OS_LINUX) {
            try {
                eventLoopGroup = new EpollEventLoopGroup(numThreads, threadFactory);
            } catch (UnsatisfiedLinkError e) {
                eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
            }
        } else {
            eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
        }
        workerGroup = eventLoopGroup;

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(workerGroup, workerGroup);
        if (workerGroup instanceof EpollEventLoopGroup) {
            bootstrap.channel(EpollServerSocketChannel.class);
        } else {
            bootstrap.channel(NioServerSocketChannel.class);
        }

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("frameDecoder",
                        new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
                ch.pipeline().addLast("handler", new MockServerCnx());
            }
        });
        // Bind and start to accept incoming connections.
        bootstrap.bind(brokerServicePort).sync();
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.zhucode.longio.example.service.TestClient.java

License:Open Source License

public static void main(String[] args) throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {//  w w  w .jav a 2s .c  o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        ch.pipeline().addLast("decoder", new LengthFieldBasedFrameDecoder(65536, 0, 2, 0, 2));
                        ch.pipeline().addLast("encoder", new LengthFieldPrepender(2, false));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.zhucode.longio.transport.netty.NettyConnector.java

License:Open Source License

private void runOneRawSocketServer(int port, Dispatcher dispatcher, ProtocolType pt) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);//from  ww w . j  a v a2  s.com
    b.channel(NioServerSocketChannel.class);

    b.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new LengthFieldBasedFrameDecoder(65536, 0, 2, 0, 2));
            ch.pipeline().addLast("encoder", new LengthFieldPrepender(2, false));
            ch.pipeline().addLast(new IdleStateHandler(6000, 3000, 0));
            ch.pipeline().addLast(new RawSocketHandler(NettyConnector.this, dispatcher, callbackDispatcher,
                    getProtocolParser(pt)));
        }

    });
    b.option(ChannelOption.SO_BACKLOG, 4096);

    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f;
    try {
        f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.zhucode.longio.transport.netty.NettyConnector.java

License:Open Source License

private Client runOneRawSocketClient(String host, int port, ProtocolType pt) {

    return new NettyClient(this, host, port, new AbstarctClientChannelInitializer() {

        @Override/*from www  .j a v  a  2  s  . c o m*/
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast("decoder", new LengthFieldBasedFrameDecoder(65536, 0, 2, 0, 2));
            p.addLast("encoder", new LengthFieldPrepender(2, false));
            p.addLast("handler",
                    new RawSocketClientHandler(client, NettyConnector.this, getProtocolParser(pt)));
        }
    });
}

From source file:de.ocarthon.core.network.tcp.TCPClient.java

License:Apache License

public void initBootstrap() {
    this.bootstrap = new Bootstrap();
    this.bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
        @Override/*  w w w .  jav  a2  s  .  c  om*/
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();

            // TLS
            if (useTls) {
                p.addLast(SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE)
                        .newHandler(ch.alloc()));
            }

            p.addLast(lengthPrepender);
            p.addLast(new LengthFieldBasedFrameDecoder(65535 /* (2^16)-1 */, 0, lengthBytes, 0, lengthBytes));

            if (pipelineCodec != null) {
                pipelineCodec.accept(p);
            }

            p.addLast(handler);
        }
    });
}

From source file:de.ocarthon.core.network.tcp.TCPServer.java

License:Apache License

public void initBootstrap() throws CertificateException, SSLException {
    SelfSignedCertificate cert = new SelfSignedCertificate();
    this.serverSslContext = SslContext.newServerContext(cert.certificate(), cert.privateKey());

    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {
                @Override/*from ww w .j av a 2s . c  om*/
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();

                    if (useTls) {
                        p.addLast(serverSslContext.newHandler(ch.alloc()));
                    }

                    p.addLast(lengthPrepender);
                    p.addLast(new LengthFieldBasedFrameDecoder(65535, 0, lengthBytes, 0, lengthBytes));

                    if (pipelineCodec != null) {
                        pipelineCodec.accept(p);
                    }

                    p.addLast(handler);
                }
            });
}

From source file:de.saxsys.synchronizefx.netty.tcp.LengthFieldBasedCodec.java

License:Open Source License

@Override
public void addToPipeline(final ChannelPipeline pipeline) {
    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
    pipeline.addLast(new LengthFieldPrepender(4));
}

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

License:Apache License

public void start() throws Exception {
    if (ssl) {//from   w  w  w  .j  a  va2 s  . c  om
        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) {
        callbackExecutorQueue = new SynchronousQueue<Runnable>();
        callbackExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
                callbackExecutorQueue, threadFactory);
    } else {
        callbackExecutorQueue = new LinkedBlockingQueue<Runnable>();
        callbackExecutor = new ThreadPoolExecutor(callbackThreads, callbackThreads, 0L, TimeUnit.MILLISECONDS,
                callbackExecutorQueue, threadFactory);
    }
    statsLogger.registerGauge("callbacksqueue", new Gauge<Integer>() {
        @Override
        public Integer getDefaultValue() {
            return 0;
        }

        @Override
        public Integer getSample() {
            return callbackExecutorQueue.size();
        }

    });
    InetSocketAddress address = new InetSocketAddress(host, port);
    LOGGER.log(Level.SEVERE, "Starting HerdDB network server at {0}:{1}", new Object[] { host, port + "" });
    if (address.isUnresolved()) {
        throw new IOException("Bind address " + host + ":" + port + " cannot be resolved");
    }
    ChannelInitializer<io.netty.channel.Channel> channelInitialized = new ChannelInitializer<io.netty.channel.Channel>() {
        @Override
        public void initChannel(io.netty.channel.Channel ch) throws Exception {
            NettyChannel session = new NettyChannel("unnamed", ch, callbackExecutor);
            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("messagedecoder", new ProtocolMessageDecoder());
            ch.pipeline().addLast(new ServerInboundMessageHandler(session));
        }
    };
    if (enableRealNetwork) {
        if (NetworkUtils.isEnableEpoolNative()) {
            bossGroup = new EpollEventLoopGroup(workerThreads);
            workerGroup = new EpollEventLoopGroup(workerThreads);
            LOGGER.log(Level.FINE, "Using netty-native-epoll network type");
        } else {
            bossGroup = new NioEventLoopGroup(workerThreads);
            workerGroup = new NioEventLoopGroup(workerThreads);
            LOGGER.log(Level.FINE, "Using nio network type");
        }

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NetworkUtils.isEnableEpoolNative() ? EpollServerSocketChannel.class
                        : NioServerSocketChannel.class)
                .childHandler(channelInitialized).option(ChannelOption.SO_BACKLOG, 128);
        ChannelFuture f = b.bind(address).sync();
        this.channel = f.channel();

    }

    if (enableJVMNetwork) {
        localBossGroup = new DefaultEventLoopGroup(workerThreads);
        localWorkerGroup = new DefaultEventLoopGroup(workerThreads);
        ServerBootstrap b_local = new ServerBootstrap();
        b_local.group(localBossGroup, localWorkerGroup).channel(LocalServerChannel.class)
                .childHandler(channelInitialized);

        String hostAddress = NetworkUtils.getAddress(address);
        LocalServerRegistry.registerLocalServer(hostAddress, port, ssl);

        ChannelFuture local_f = b_local.bind(new LocalAddress(hostAddress + ":" + port + ":" + ssl)).sync();
        this.local_channel = local_f.channel();
    }

}

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

License:Apache License

public static NettyChannel connect(String host, int port, boolean ssl, int connectTimeout, int socketTimeout,
        ChannelEventListener receiver, final ExecutorService callbackExecutor,
        final MultithreadEventLoopGroup networkGroup, final DefaultEventLoopGroup localEventsGroup)
        throws IOException {
    try {/*  w w  w  .j  a v  a  2s.c  o m*/
        final SslContext sslCtx = !ssl ? null
                : SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

        Class<? extends Channel> channelType;

        InetSocketAddress inet = new InetSocketAddress(host, port);
        SocketAddress address;
        String hostAddress = NetworkUtils.getAddress(inet);

        MultithreadEventLoopGroup group;
        if (LocalServerRegistry.isLocalServer(hostAddress, port, ssl)) {
            channelType = LocalChannel.class;
            address = new LocalAddress(hostAddress + ":" + port + ":" + ssl);
            group = localEventsGroup;
        } else {
            channelType = networkGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class
                    : NioSocketChannel.class;
            address = inet;
            group = networkGroup;
        }
        Bootstrap b = new Bootstrap();
        AtomicReference<NettyChannel> result = new AtomicReference<>();

        b.group(group).channel(channelType).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    public void initChannel(Channel ch) throws Exception {
                        try {
                            NettyChannel channel = new NettyChannel(host + ":" + port, ch, callbackExecutor);
                            result.set(channel);
                            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("messagedecoder", new ProtocolMessageDecoder());
                            ch.pipeline().addLast(new ClientInboundMessageHandler(channel));
                        } catch (Throwable t) {
                            LOGGER.log(Level.SEVERE, "error connecting", t);
                            ch.close();
                        }
                    }
                });

        LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}",
                new Object[] { host, port, ssl, address });
        b.connect(address).sync();
        NettyChannel nettyChannel = result.get();
        if (!nettyChannel.isValid()) {
            throw new IOException("returned channel is not valid");
        }
        return nettyChannel;
    } catch (InterruptedException ex) {
        throw new IOException(ex);
    }

}

From source file:io.airlift.drift.transport.netty.LengthPrefixedMessageFraming.java

License:Apache License

@Override
public void addFrameHandlers(ChannelPipeline pipeline) {
    pipeline.addLast("frameEncoder", new LengthFieldPrepender(Integer.BYTES));
    pipeline.addLast("frameDecoder",
            new LengthFieldBasedFrameDecoder(maxFrameSize, 0, Integer.BYTES, 0, Integer.BYTES));
}