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.nus.mazegame.server.GameServer.java

public static void init(int port, int x, int y, int treasure, boolean isSlave) throws Exception {
    GameService.gameService = new GameService(x, y, treasure, isSlave);

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  www .  j a  v  a2  s.  c  o m*/
        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 {
                        ChannelPipeline p = ch.pipeline();
                        // Decoders
                        p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                        p.addLast("bytesDecoder", new ByteArrayDecoder());

                        // Encoder
                        p.addLast("frameEncoder", new LengthFieldPrepender(4));
                        p.addLast("bytesEncoder", new ByteArrayEncoder());
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new GameServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(port).sync();
        Logger.getLogger(GameServerHandler.class.getName()).log(Level.INFO, "Server started...");
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.phei.netty.codec.msgpack.EchoClientV2.java

License:Apache License

public void run() throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*  ww w . j  a va 2s  .  co  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("frameDecoder",
                                new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
                        ch.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
                        ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
                        ch.pipeline().addLast("msgpack encoder", new MsgpackEncoder());
                        ch.pipeline().addLast(new EchoClientHandler(sendNumber));
                    }
                });

        // 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.phei.netty.codec.msgpack.EchoServerV2.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup acceptorGroup = new NioEventLoopGroup();
    EventLoopGroup IOGroup = new NioEventLoopGroup();
    try {//from  w ww.  java 2 s  . co m
        ServerBootstrap b = new ServerBootstrap();
        b.group(acceptorGroup, IOGroup).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 {
                        ch.pipeline().addLast("frameDecoder",
                                new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
                        ch.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
                        ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
                        ch.pipeline().addLast("msgpack encoder", new MsgpackEncoder());
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(port).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        acceptorGroup.shutdownGracefully();
        IOGroup.shutdownGracefully();
    }
}

From source file:com.splicemachine.olap.AsyncOlapNIOLayer.java

License:Apache License

public AsyncOlapNIOLayer(String host, int port) {
    InetSocketAddress socketAddr = new InetSocketAddress(host, port);
    Bootstrap bootstrap = new Bootstrap();
    NioEventLoopGroup group = new NioEventLoopGroup(5,
            new ThreadFactoryBuilder().setNameFormat("olapClientWorker-%d").setDaemon(true)
                    .setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                        @Override
                        public void uncaughtException(Thread t, Throwable e) {
                            LOG.error("[" + t.getName() + "] Unexpected error in AsyncOlapNIO pool: ", e);
                        }/*from  www  .  j a  v a  2 s  .  c om*/
                    }).build());
    bootstrap.channel(NioSocketChannel.class).group(group).option(ChannelOption.SO_KEEPALIVE, true)
            .remoteAddress(socketAddr);

    //TODO -sf- this may be excessive network usage --consider a bounded pool to prevent over-connection?
    this.channelPool = new SimpleChannelPool(bootstrap, new AbstractChannelPoolHandler() {
        @Override
        public void channelCreated(Channel channel) throws Exception {
            ChannelPipeline p = channel.pipeline();
            p.addLast("frameEncoder", new LengthFieldPrepender(4));
            p.addLast("protobufEncoder", new ProtobufEncoder());
            p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1 << 30, 0, 4, 0, 4));
            p.addLast("protobufDecoder", decoder);
        }
    });
    executorService = group;
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClientSession.java

License:Apache License

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

    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override/* ww  w  .  j  a  v  a  2  s  .c o  m*/
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            bumpTimeout(ctx);
            ctx.fireChannelRead(msg);
        }
    });

    // first four bytes are length prefix of message, strip first four bytes.
    pipeline.addLast(new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
    pipeline.addLast(new NativeRpcDecoder());
    pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
        @Override
        protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
            if (msg instanceof NativeRpcError) {
                final NativeRpcError error = (NativeRpcError) msg;

                if (log.isTraceEnabled()) {
                    log.trace("[{}] remote error: {}", ctx.channel(), error.getMessage());
                }

                future.fail(new NativeRpcRemoteException(address, error.getMessage()));
                ctx.channel().close();
                return;
            }

            if (msg instanceof NativeRpcResponse) {
                if (log.isTraceEnabled()) {
                    log.trace("[{}] response: cancelling heartbeat", ctx.channel());
                }

                try {
                    handleResponse((NativeRpcResponse) msg);
                } catch (Exception e) {
                    future.fail(new Exception("Failed to handle response", e));
                }

                return;
            }

            if (msg instanceof NativeRpcHeartBeat) {
                if (log.isTraceEnabled()) {
                    log.trace("[{}] heartbeat: delaying timeout by {}ms", ctx.channel(), heartbeatInterval);
                }

                bumpTimeout(ctx);
                return;
            }

            throw new IllegalArgumentException("unable to handle type: " + msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            future.fail(cause);
            ctx.channel().close();
        }
    });

    pipeline.addLast(new LengthFieldPrepender(4));
    pipeline.addLast(new NativeRpcEncoder());
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClientSessionInitializer.java

License:Apache License

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

    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override//from   www .  j  av  a 2s  .  co m
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            bumpTimeout(ctx);
            ctx.fireChannelRead(msg);
        }
    });

    // first four bytes are length prefix of message, strip first four bytes.
    pipeline.addLast(new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
    pipeline.addLast(new NativeRpcDecoder());
    pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
        @Override
        protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
            if (msg instanceof NativeRpcError) {
                final NativeRpcError error = (NativeRpcError) msg;

                if (log.isTraceEnabled()) {
                    log.trace("[{}] remote error: {}", ctx.channel(), error.getMessage());
                }

                future.fail(new NativeRpcRemoteException(address, error.getMessage()));
                ctx.channel().close();
                return;
            }

            if (msg instanceof NativeRpcResponse) {
                if (log.isTraceEnabled()) {
                    log.trace("[{}] response: cancelling heartbeat", ctx.channel());
                }

                final Timeout old = heartbeatTimeout.getAndSet(null);

                if (old != null) {
                    old.cancel();
                }

                final NativeRpcResponse response = (NativeRpcResponse) msg;
                final R responseBody = mapper.readValue(response.getBody(), expected);
                future.resolve(responseBody);
                return;
            }

            if (msg instanceof NativeRpcHeartBeat) {
                if (log.isTraceEnabled()) {
                    log.trace("[{}] heartbeat: delaying timeout by {}ms", ctx.channel(), heartbeatInterval);
                }

                bumpTimeout(ctx);
                return;
            }

            throw new IllegalArgumentException("unable to handle type: " + msg);
        }
    });

    pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            future.fail(cause);
        }
    });

    pipeline.addLast(new LengthFieldPrepender(4));
    pipeline.addLast(new NativeRpcEncoder());
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcServerSession.java

License:Apache License

@Override
protected void initChannel(final SocketChannel ch) throws Exception {
    final AtomicReference<Timeout> heartbeatTimeout = new AtomicReference<>();

    final ChannelPipeline pipeline = ch.pipeline();
    // first four bytes are length prefix of message, strip first four bytes.
    pipeline.addLast(new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
    pipeline.addLast(new NativeRpcDecoder());
    pipeline.addLast(new ChannelHandler(heartbeatTimeout));

    pipeline.addLast(new LengthFieldPrepender(4));
    pipeline.addLast(new NativeRpcEncoder());
}

From source file:com.srotya.sidewinder.core.ingress.binary.NettyBinaryIngestionServer.java

License:Apache License

public void start() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    ServerBootstrap bs = new ServerBootstrap();
    channel = bs.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_RCVBUF, 10485760).option(ChannelOption.SO_SNDBUF, 10485760)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*w w  w  .java2s  .com*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new LengthFieldBasedFrameDecoder(3000, 0, 4, 0, 4));
                    p.addLast(new SeriesDataPointDecoder());
                    p.addLast(new SeriesDataPointWriter(storageEngine));
                }

            }).bind("localhost", 9927).sync().channel();
}

From source file:com.yahoo.pulsar.broker.service.ServerCnxTest.java

License:Apache License

private void resetChannel() throws Exception {
    int MaxMessageSize = 5 * 1024 * 1024;
    if (channel != null && channel.isActive()) {
        serverCnx.close();/*from   w  w w  . j  a v  a  2s .  com*/
        channel.close().get();
    }
    serverCnx = new ServerCnx(brokerService);
    channel = new EmbeddedChannel(new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4), serverCnx);
}

From source file:com.yahoo.pulsar.broker.service.utils.ClientChannelHelper.java

License:Apache License

public ClientChannelHelper() {
    int MaxMessageSize = 5 * 1024 * 1024;
    channel = new EmbeddedChannel(new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4), decoder);
}