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, int lengthAdjustment) 

Source Link

Document

Creates a new instance.

Usage

From source file:com.github.spapageo.jannel.channel.ChannelHandlerProvider.java

License:Open Source License

public ChannelHandler getChangeHandler(HandlerType handlerType, ClientSessionConfiguration sessionConfiguration,
        SessionCallbackHandler clientSession, Transcoder transcoder) {
    switch (handlerType) {
    case MESSAGE_LOGGER:
        return MESSAGE_LOGGER;
    case SESSION_WRAPPER:
        return new SessionWrapperHandler(clientSession);
    case WRITE_TIMEOUT_HANDLER:
        return new WriteTimeoutHandler(sessionConfiguration.getWriteTimeout(), TimeUnit.MILLISECONDS);
    case MESSAGE_DECODER:
        return new MessageDecoder(transcoder);
    case MESSAGE_ENCODER:
        return new MessageEncoder(transcoder);
    case LENGTH_FRAME_DECODER:
        return new LengthFieldBasedFrameDecoder(MAXIMUM_MESSAGE_BYTE_SIZE, MESSAGE_FIELD_OFFSET,
                LENGTH_FIELD_SIZE, 0, LENGTH_FIELD_SIZE);
    case LENGTH_FRAME_ENCODER:
        return new LengthFieldPrepender(LENGTH_FIELD_SIZE, false);
    default://w  w  w  . j a  v a 2  s .c o  m
        throw new IllegalArgumentException("Invalid handler type");
    }
}

From source file:com.hipishare.chat.securetest.SecureChatClientInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    LOG.info("channel?");
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    //        pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    // On top of the SSL handler, add the text line codec.
    //        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    //        pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4));
    pipeline.addLast(new LengthFieldPrepender(4, false));
    /*pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());*/
    pipeline.addLast(new MsgObjectDecoder());
    pipeline.addLast(new MsgObjectEncoder());
    //        pipeline.addLast(new LoggingHandler(LogLevel.INFO));

    // and then business logic.
    pipeline.addLast(new SecureChatClientHandler());
}

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 {/*from   w  w  w.j av  a2 s .  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   w w w .  j  a va  2s  .c  o  m
    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 w  w  w.  j  a v  a  2 s  . com*/
        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:james.learn.netty.echo2.EchoClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO// ww w. java 2  s . c  o  m
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        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 {
                        /* ByteBuf delimiter = Unpooled.copiedBuffer("$_"
                            .getBytes());
                         ch.pipeline().addLast(
                            new DelimiterBasedFrameDecoder(1024,
                               delimiter));*/
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4));
                        ch.pipeline().addLast(new LengthFieldPrepender(4, false));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();

        // 
        f.channel().closeFuture().sync();
    } finally {
        // NIO
        group.shutdownGracefully();
    }
}

From source file:james.learn.netty.echo2.EchoServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO/* ww  w  .  j a v  a 2s  . c o  m*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        /*ByteBuf delimiter = Unpooled.copiedBuffer("$_"
                           .getBytes());
                        ch.pipeline().addLast(
                           new DelimiterBasedFrameDecoder(1024,
                              delimiter));*/
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4));
                        ch.pipeline().addLast(new LengthFieldPrepender(4, false));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

        // ???
        ChannelFuture f = b.bind(port).sync();

        // ???
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.apache.helix.ipc.netty.NettyHelixIPCService.java

License:Apache License

/**
 * Starts message handling server, creates client bootstrap, and bootstraps partition routing
 * table./*from   w w w . j  a v a 2  s.c om*/
 */
public void start() throws Exception {
    if (isShutdown.getAndSet(false)) {
        eventLoopGroup = new NioEventLoopGroup();

        statTxMsg = metricRegistry.meter(MetricRegistry.name(NettyHelixIPCService.class, "txMsg"));
        statRxMsg = metricRegistry.meter(MetricRegistry.name(NettyHelixIPCService.class, "rxMsg"));
        statTxBytes = metricRegistry.meter(MetricRegistry.name(NettyHelixIPCService.class, "txBytes"));
        statRxBytes = metricRegistry.meter(MetricRegistry.name(NettyHelixIPCService.class, "rxBytes"));
        statChannelOpen = metricRegistry
                .counter(MetricRegistry.name(NettyHelixIPCService.class, "channelOpen"));
        statError = metricRegistry.counter(MetricRegistry.name(NettyHelixIPCService.class, "error"));

        // Report metrics via JMX
        jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
        LOG.info("Registered JMX metrics reporter");

        new ServerBootstrap().group(eventLoopGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new LengthFieldBasedFrameDecoder(config.getMaxFrameLength(),
                                        LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT,
                                        INITIAL_BYTES_TO_STRIP));
                        socketChannel.pipeline().addLast(new NettyHelixIPCCallbackHandler(
                                config.getInstanceName(), callbacks, statRxMsg, statRxBytes));
                    }
                }).bind(new InetSocketAddress(config.getPort()));
        LOG.info("Listening on port " + config.getPort());

        clientBootstrap = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new LengthFieldPrepender(LENGTH_FIELD_LENGTH, true));
                        socketChannel.pipeline().addLast(new NettyHelixIPCBackPressureHandler());
                    }
                });
    }
}

From source file:org.didinem.client.RpcClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO/*from w ww  .  j a va  2s.c om*/
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        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 {
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4, 0, 4));
                        ch.pipeline().addLast(new LengthFieldPrepender(4, false));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new RpcClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();
        channel = f.channel();

    } finally {
        // NIO
        group.shutdownGracefully();
    }
}