Example usage for io.netty.buffer ByteBuf readableBytes

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

Introduction

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

Prototype

public abstract int readableBytes();

Source Link

Document

Returns the number of readable bytes which is equal to (this.writerIndex - this.readerIndex) .

Usage

From source file:buildcraft.core.network.RPCHandler.java

License:Minecraft Mod Public

private PacketRPCPipe createRCPPacket(Pipe pipe, String method, Object... actuals) {
    ByteBuf data = Unpooled.buffer();

    try {//from   ww  w. ja  v  a2s .  co m
        TileEntity tile = pipe.container;

        // In order to save space on message, we assuming dimensions ids
        // small. Maybe worth using a varint instead
        data.writeShort(tile.getWorldObj().provider.dimensionId);
        data.writeInt(tile.xCoord);
        data.writeInt(tile.yCoord);
        data.writeInt(tile.zCoord);

        writeParameters(method, data, actuals);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    byte[] bytes = new byte[data.readableBytes()];
    data.readBytes(bytes);

    return new PacketRPCPipe(bytes);
}

From source file:buildcraft.core.network.RPCHandler.java

License:Minecraft Mod Public

private PacketRPCTile createRCPPacket(TileEntity tile, String method, Object... actuals) {
    ByteBuf data = Unpooled.buffer();

    try {// w w w.  jav  a2  s .  c om
        writeParameters(method, data, actuals);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    byte[] bytes = new byte[data.readableBytes()];
    data.readBytes(bytes);

    return new PacketRPCTile(tile, bytes);
}

From source file:buildcraft.lib.tile.TileBC_Neptune.java

License:Mozilla Public License

@Override
public NBTTagCompound getUpdateTag() {
    ByteBuf buf = Unpooled.buffer();
    buf.writeShort(NET_RENDER_DATA);//from   www  .  j  a va 2s  .c om
    writePayload(NET_RENDER_DATA, new PacketBufferBC(buf), world.isRemote ? Side.CLIENT : Side.SERVER);
    byte[] bytes = new byte[buf.readableBytes()];
    buf.readBytes(bytes);

    NBTTagCompound nbt = super.getUpdateTag();
    nbt.setByteArray("d", bytes);
    return nbt;
}

From source file:c5db.control.ClientHttpProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
    Class<?> messageType = msg.getClass();

    LowCopyProtobufOutput outputSerializer = new LowCopyProtobufOutput();
    msg.cachedSchema().writeTo(outputSerializer, msg);
    List<ByteBuffer> serializedBuffers = outputSerializer.buffer.finish();
    ByteBuf requestContent = Unpooled.wrappedBuffer(serializedBuffers.toArray(new ByteBuffer[] {}));

    DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.POST,
            "foo", requestContent);

    httpRequest.headers().set(HttpProtostuffConstants.PROTOSTUFF_HEADER_NAME, messageType.getName());
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream");
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestContent.readableBytes());

    out.add(httpRequest);/* w ww  .j  ava  2s .  c om*/
}

From source file:c5db.discovery.InboundHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    SocketAddress remoteAddress = ctx.channel().remoteAddress();
    SocketAddress localAddress = ctx.channel().localAddress();

    System.out.println("Got message from " + remoteAddress + " to me at: " + localAddress);
    System.out.println("  It was SOOO big: " + msg.readableBytes());

}

From source file:c5db.replication.ReplicationWireMessageTest.java

License:Apache License

@Test
public void testSimpleSerialization() throws Exception {
    RequestVote rv = new RequestVote(1, 22222, 34, 22);
    ReplicationWireMessage rwm = new ReplicationWireMessage(1, 1, 0, "quorumId", false, rv, null, null, null,
            null, null);/*  w  w  w .j  a va2  s .c  o  m*/

    LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput(new LinkBuffer(24));
    rwm.writeTo(lcpo, rwm);
    List<ByteBuffer> serBufs = lcpo.buffer.finish();
    logBufsInformation("ReplicationWireMessage", serBufs);

    ByteBuf b = Unpooled.wrappedBuffer(serBufs.toArray(new ByteBuffer[serBufs.size()]));
    System.out.println("ByteBuf info = " + b);
    System.out.println("ByteBuf size = " + b.readableBytes());
    assertEquals(lcpo.buffer.size(), b.readableBytes());

    System.out.println("rwm = " + rwm);
}

From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//w  w w .ja v  a  2  s. co m
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.getUri())) {
        ByteBuf content = ServerIndexPageWebSocket.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpHeaders.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.getUri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:cat.tbq.hospital.nio.echoExample.EchoClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf byteBuf = (ByteBuf) msg;
    int size = byteBuf.readableBytes();
    for (int i = 0; i < size; i++) {
        System.out.println("client===" + (char) byteBuf.getByte(i));
        ;/*from w  ww  . ja  v a 2 s.  c  o  m*/
    }
    //        ctx.write(msg);
}

From source file:cat.tbq.hospital.nio.echoExample.EchoServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf byteBuf = (ByteBuf) msg;
    int size = byteBuf.readableBytes();
    for (int i = 0; i < size; i++) {
        System.out.println("===" + (char) byteBuf.getByte(i));
        ;/*from w w  w  .ja v  a  2  s  . co m*/
    }
    ByteBuf firstMessage = Unpooled.buffer(20);
    firstMessage.writeBytes("hello how are you".getBytes());
    ctx.writeAndFlush(firstMessage);
}

From source file:cc.agentx.client.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    boolean proxyMode = isAgentXNeeded(request.host());
    log.info("\tClient -> Proxy           \tTarget {}:{} [{}]", request.host(), request.port(),
            proxyMode ? "AGENTX" : "DIRECT");
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new FutureListener<Channel>() {
        @Override//  w  ww. ja v  a2 s .  c o  m
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(channelFuture -> {
                            ByteBuf byteBuf = Unpooled.buffer();
                            request.encodeAsByteBuf(byteBuf);
                            if (byteBuf.hasArray()) {
                                byte[] xRequestBytes = new byte[byteBuf.readableBytes()];
                                byteBuf.getBytes(0, xRequestBytes);

                                if (proxyMode) {
                                    // handshaking to remote proxy
                                    xRequestBytes = requestWrapper.wrap(xRequestBytes);
                                    outboundChannel.writeAndFlush(Unpooled.wrappedBuffer(
                                            exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes)));
                                }

                                // task handover
                                ReferenceCountUtil.retain(request); // auto-release? a trap?
                                ctx.pipeline().remove(XConnectHandler.this);
                                outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(),
                                        proxyMode ? wrapper : rawWrapper, false));
                                ctx.pipeline().addLast(new XRelayHandler(outboundChannel,
                                        proxyMode ? wrapper : rawWrapper, true));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));

                if (ctx.channel().isActive()) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    });

    String host = request.host();
    int port = request.port();
    if (host.equals(config.getConsoleDomain())) {
        host = "localhost";
        port = config.getConsolePort();
    } else if (proxyMode) {
        host = config.getServerHost();
        port = config.getServerPort();
    }

    // ping target
    bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.channel().writeAndFlush(
                                new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                        if (ctx.channel().isActive()) {
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        }
                    }
                }
            });
}