Example usage for io.netty.buffer ByteBuf readBytes

List of usage examples for io.netty.buffer ByteBuf readBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readBytes.

Prototype

public abstract ByteBuf readBytes(ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the current readerIndex until the destination's position reaches its limit, and increases the readerIndex by the number of the transferred bytes.

Usage

From source file:com.github.gregwhitaker.requestreply.Client.java

License:Apache License

public void start() throws Exception {
    Publisher<ClientTcpDuplexConnection> publisher = ClientTcpDuplexConnection.create(remoteAddress,
            new NioEventLoopGroup(1));

    ClientTcpDuplexConnection duplexConnection = RxReactiveStreams.toObservable(publisher).toBlocking().last();
    ReactiveSocket reactiveSocket = DefaultReactiveSocket.fromClientConnection(duplexConnection,
            ConnectionSetupPayload.create("UTF-8", "UTF-8"), t -> t.printStackTrace());

    reactiveSocket.startAndWait();//from   w  ww  .  j av a2 s .  c  om

    // Create an observable that emits messages at a specific interval.
    Publisher<Payload> requestStream = RxReactiveStreams.toPublisher(
            Observable.interval(1_000, TimeUnit.MILLISECONDS).onBackpressureDrop().map(i -> new Payload() {
                @Override
                public ByteBuffer getData() {
                    return ByteBuffer.wrap(("YO " + i).getBytes());
                }

                @Override
                public ByteBuffer getMetadata() {
                    return Frame.NULL_BYTEBUFFER;
                }
            }));

    final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE);

    requestStream.subscribe(new Subscriber<Payload>() {
        @Override
        public void onSubscribe(Subscription s) {
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(Payload payload) {
            ByteBuf buffer = Unpooled.buffer(payload.getData().capacity());
            buffer.writeBytes(payload.getData());

            byte[] bytes = new byte[buffer.capacity()];
            buffer.readBytes(bytes);

            System.out.println("Client Sent: " + new String(bytes));

            reactiveSocket.requestResponse(payload).subscribe(new Subscriber<Payload>() {
                @Override
                public void onSubscribe(Subscription s) {
                    s.request(Long.MAX_VALUE);
                }

                @Override
                public void onNext(Payload payload) {
                    ByteBuf buffer = Unpooled.buffer(payload.getData().capacity());
                    buffer.writeBytes(payload.getData());

                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.readBytes(bytes);

                    System.out.println("Client Received: " + new String(bytes));

                    latch.countDown();
                }

                @Override
                public void onError(Throwable t) {
                    latch.countDown();
                }

                @Override
                public void onComplete() {
                    latch.countDown();
                }
            });
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {

        }
    });

    latch.await();
    System.exit(0);
}

From source file:com.github.jrialland.ajpclient.impl.handlers.AjpMessagesHandler.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> _out)
        throws Exception {

    // read magic bytes
    for (final byte element : CONTAINER_MAGIC) {
        final byte b = in.readByte();
        if (b != element) {
            final String hex = "0" + Integer.toHexString(b);
            getLog().warn("skipping unexpected byte 0x" + hex.substring(hex.length() - 2));
            return;
        }//from  ww  w.  j  a v  a2s.c o m
    }

    // read data length
    final int length = in.readUnsignedShort();

    // read message type prefix
    final int prefix = in.readUnsignedByte();
    final MessageType msgType = MessageType.forPrefix(prefix);
    if (msgType == null) {
        throw new IllegalStateException("unknown message prefix code : " + prefix);
    } else if (getLog().isDebugEnabled()) {
        final String type = MessageType.forPrefix(prefix).name().toUpperCase();
        getLog().debug(String.format("Received : %s (%s), payload size = %s bytes", type, prefix, length));
    }

    // CPONG
    if (prefix == PREFIX_CPONG) {
        getCallback(ctx.channel()).handleCPongMessage();
        return;
    }

    // SEND_HEADERS
    else if (prefix == PREFIX_SEND_HEADERS) {
        // store response status and content length;
        expectedBytes = readHeaders(ctx, in);
        return;
    }

    // SEND_BODY_CHUNK
    else if (prefix == PREFIX_SEND_BODY_CHUNK) {
        final int chunkLength = in.readUnsignedShort();
        if (chunkLength > 0) {
            getCallback(ctx.channel()).handleSendBodyChunkMessage(in.readBytes(chunkLength));

            // update expected bytes counter

            if (expectedBytes != null) {
                expectedBytes -= chunkLength;
            }
        }

        // consume an extra byte, as it seems that there is always a useless
        // 0x00 following data in these packets
        in.readByte();
        return;
    }

    // END_RESPONSE
    else if (prefix == PREFIX_END_RESPONSE) {
        final boolean reuse = in.readBoolean();
        getCallback(ctx.channel()).handleEndResponseMessage(reuse);
        return;
    }

    // GET_BODY_CHUNK
    else if (prefix == PREFIX_GET_BODY_CHUNK) {
        final int requestedLength = in.readUnsignedShort();
        getCallback(ctx.channel()).handleGetBodyChunkMessage(requestedLength);
        return;
    }
}

From source file:com.github.jrialland.ajpclient.impl.handlers.AjpMessagesHandler.java

License:Apache License

protected String readString(final ByteBuf in) {
    in.markReaderIndex();/*from ww  w.  j a va2 s .  c o  m*/
    final int b0 = in.readUnsignedByte();
    if (b0 == 0xff) {
        return null;
    }
    in.resetReaderIndex();
    final int length = in.readUnsignedShort();
    final byte[] data = new byte[length];
    in.readBytes(data);

    // skip trailing \0
    in.readByte();

    return new String(data);
}

From source file:com.github.jrialland.ajpclient.impl.handlers.OutgoingFramesLogger.java

License:Apache License

@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
        throws Exception {

    if (msg == null) {
        getLog().debug(">>> (null)");
    } else if (msg instanceof ByteBuf) {

        final ByteBuf buf = (ByteBuf) msg;
        buf.markReaderIndex();/*from w  w  w. j av  a  2 s.c  o  m*/

        final byte[] data = new byte[buf.readableBytes()];
        buf.readBytes(data);
        getLog().debug(">>> " + bytesToHex(data));

        buf.resetReaderIndex();

    } else {
        getLog().debug(">>> " + msg.toString());
    }

    // pass to the next handler in the chain
    super.write(ctx, msg, promise);
}

From source file:com.github.lburgazzoli.quickfixj.transport.netty.codec.NettyMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (m_msgLength == -1) {
        if (in.readableBytes() >= FIXCodecHelper.MSG_MIN_BYTES) {
            int ridx = in.readerIndex();
            int bssohidx = in.indexOf(ridx, ridx + 12, FIXCodecHelper.BYTE_SOH);
            int blsohidx = in.indexOf(ridx + 12, ridx + 20, FIXCodecHelper.BYTE_SOH);

            // check the existence of:
            // - BeginString 8=
            // - BodyLength  9=
            if (in.getByte(ridx) == FIXCodecHelper.BYTE_BEGIN_STRING
                    && in.getByte(ridx + 1) == FIXCodecHelper.BYTE_EQUALS
                    && in.getByte(bssohidx + 1) == FIXCodecHelper.BYTE_BODY_LENGTH
                    && in.getByte(bssohidx + 2) == FIXCodecHelper.BYTE_EQUALS) {

                int bodyLength = 0;
                for (int i = bssohidx + 3; i < blsohidx; i++) {
                    bodyLength *= 10;/*from   w  w w. ja  v a 2  s  .  co  m*/
                    bodyLength += (in.getByte(i) - '0');
                }

                m_msgLength = 1 + bodyLength + (blsohidx - ridx) + FIXCodecHelper.MSG_CSUM_LEN;
            } else {
                throw new Error("Unexpected state (header)");
            }
        }
    }

    if (m_msgLength != -1 && in.readableBytes() >= m_msgLength) {
        if (in.readableBytes() >= m_msgLength) {
            byte[] rv = new byte[m_msgLength];
            in.readBytes(rv);

            //TODO: validate checksum
            out.add(rv);

            m_msgLength = -1;
        } else {
            throw new Error("Unexpected state (body)");
        }
    }
}

From source file:com.github.liyp.netty.App.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {// ww w  .j av a  2s .  com
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ReplayingDecoder() {
                            @Override
                            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                                    throws Exception {
                                short magicHeader = in.readShort();
                                logger.debug("Receive magic header: {}.", magicHeader);
                                if (magicHeader != HEADER) {
                                    logger.error("Receive illegal magic header: {}, close channel: {}.",
                                            magicHeader, ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                short dataLen = in.readShort();
                                logger.debug("Receive message data length: {}.", dataLen);
                                if (dataLen < 0) {
                                    logger.error("Data length is negative, close channel: {}.",
                                            ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                ByteBuf payload = in.readBytes(dataLen);
                                String cloudMsg = payload.toString(CharsetUtil.UTF_8);
                                logger.debug("Receive data: {}.", cloudMsg);
                                out.add(cloudMsg);
                            }
                        }).addLast(new MessageToByteEncoder<String>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out)
                                    throws Exception {
                                out.writeBytes(msg.getBytes());
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("start receive msg...");
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                logger.info("receive msg: {}", msg);
                                logger.info("echo msg");
                                ctx.writeAndFlush(msg);
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}

From source file:com.github.milenkovicm.kafka.protocol.Convert.java

License:Apache License

public static ByteBuf decodeBytes(ByteBuf buf) {
    int readable = decodeInteger(buf); // N => int32
    return buf.readBytes(readable); // content
}

From source file:com.github.milenkovicm.kafka.protocol.Convert.java

License:Apache License

public static String decodeString(ByteBuf buf) {
    int readable = decodeShort(buf); // N => int16
    ByteBuf bytes = buf.readBytes(readable); // content

    if (bytes.hasArray()) {
        return new String(bytes.array(), DEFAULT_CHARSET);
    } else {//from  w  ww. j  av  a 2s . c  om
        byte[] array = new byte[readable];
        bytes.readBytes(array);
        return new String(array, DEFAULT_CHARSET);
    }
}

From source file:com.github.mrstampy.gameboot.otp.websocket.client.WebSocketHandler.java

License:Open Source License

private byte[] extractBytes(Object msg) {
    BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;

    ByteBuf buf = frame.content();

    byte[] b = new byte[buf.readableBytes()];

    buf.readBytes(b);

    return b;//from w  ww .  ja  v a  2s.c om
}

From source file:com.github.mrstampy.kitchensync.netty.handler.AbstractKiSyNettyHandler.java

License:Open Source License

/**
 * Bytes./* w  ww .  j a  v a 2  s  . co  m*/
 *
 * @param msg
 *          the msg
 * @return the byte[]
 */
protected byte[] bytes(DatagramPacket msg) {
    ByteBuf content = msg.content();

    int num = content.readableBytes();
    byte[] message = new byte[num];
    content.readBytes(message);

    return message;
}