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:com.fanavard.challenge.server.websocket.server.WebSocketServerHandler.java

License:Apache License

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

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

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

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

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.uri())) {
        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:com.farsunset.cim.sdk.android.filter.ClientMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext arg0, ByteBuf buffer, List<Object> queue) throws Exception {

    /**/*from  w  ww  . j  av  a2 s .  c om*/
     * ?3?
     */
    if (buffer.readableBytes() < CIMConstant.DATA_HEADER_LENGTH) {
        return;
    }

    buffer.markReaderIndex();

    buffer.markReaderIndex();

    byte conetnType = buffer.readByte();

    byte lv = buffer.readByte();// int ?
    byte hv = buffer.readByte();// int ?

    int conetnLength = getContentLength(lv, hv);

    // ?????
    if (conetnLength > buffer.readableBytes()) {
        buffer.resetReaderIndex();
        return;
    }

    byte[] dataBytes = new byte[conetnLength];
    buffer.readBytes(dataBytes);

    Object message = mappingMessageObject(dataBytes, conetnType);

    if (message != null) {
        queue.add(message);
    }

}

From source file:com.farsunset.cim.sdk.server.filter.decoder.AppMessageDecoder.java

License:Apache License

@Override
public void decode(ChannelHandlerContext arg0, ByteBuf buffer, List<Object> queue) throws Exception {

    /**//  w ww  .j  a va  2s  .c  o m
     * ?3?
     */
    if (buffer.readableBytes() < CIMConstant.DATA_HEADER_LENGTH) {
        return;
    }

    buffer.markReaderIndex();

    byte conetnType = buffer.readByte();

    byte lv = buffer.readByte();// int ?
    byte hv = buffer.readByte();// int ?

    int conetnLength = getContentLength(lv, hv);

    // ?????
    if (conetnLength <= buffer.readableBytes()) {
        byte[] dataBytes = new byte[conetnLength];
        buffer.readBytes(dataBytes);

        Object message = mappingMessageObject(dataBytes, conetnType);
        if (message != null) {
            arg0.channel().attr(AttributeKey.valueOf(CIMSession.PROTOCOL)).set(CIMSession.NATIVEAPP);
            queue.add(message);
            return;
        }
    }

    buffer.resetReaderIndex();
}

From source file:com.farsunset.cim.sdk.server.filter.decoder.WebMessageDecoder.java

License:Apache License

@Override
public void decode(ChannelHandlerContext arg0, ByteBuf iobuffer, List<Object> queue) throws Exception {

    iobuffer.markReaderIndex();// w  w  w  .j av  a2  s  .  c om

    /**
     * ?fin??1 0 ??
     */
    byte tag = iobuffer.readByte();
    int frameFin = tag > 0 ? 0 : 1; // ?byte ?1 ?0 fin 0  1
    if (frameFin == 0) {
        iobuffer.resetReaderIndex();
        return;
    }

    /**
     * ?protobuf?? OPCODE_BINARY? OPCODE_CLOSE
     */
    int frameOqcode = tag & TAG_MASK;

    if (OPCODE_BINARY == frameOqcode) {

        byte head = iobuffer.readByte();
        byte datalength = (byte) (head & PAYLOADLEN);
        int realLength = 0;

        /**
         * Payload len7?7+16?7+64????? 0-125payload
         * data 1267????2payload data
         * 1277????8payload data
         */
        if (datalength == HAS_EXTEND_DATA) {
            realLength = iobuffer.readShort();
        } else if (datalength == HAS_EXTEND_DATA_CONTINUE) {
            realLength = (int) iobuffer.readLong();
        } else {
            realLength = datalength;
        }

        boolean masked = (head >> 7 & MASK) == 1;
        if (masked) {// ?
            // ??
            byte[] mask = new byte[4];
            iobuffer.readBytes(mask);

            byte[] data = new byte[realLength];
            iobuffer.readBytes(data);
            for (int i = 0; i < realLength; i++) {
                // ??
                data[i] = (byte) (data[i] ^ mask[i % 4]);
            }

            handleMessage(data, queue);
        }

    } else if (OPCODE_CLOSE == frameOqcode) {
        handleClose(arg0);
    } else {
        // ?
        iobuffer.readBytes(new byte[iobuffer.readableBytes()]);
    }

}

From source file:com.farsunset.cim.sdk.server.filter.ServerMessageDecoder.java

License:Apache License

private boolean tryWebsocketHandleHandshake(ChannelHandlerContext arg0, ByteBuf iobuffer, List<Object> queue) {

    iobuffer.markReaderIndex();//  w  ww  .j  a va2s .  c o m

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

    String request = new String(data);
    String secKey = getSecWebSocketKey(request);
    boolean handShake = secKey != null && Objects.equals(getUpgradeProtocol(request), CIMSession.WEBSOCKET);
    if (handShake) {
        /**
         * ?????HANDSHAKE_FRAME,?session??websocket
         */
        arg0.channel().attr(AttributeKey.valueOf(CIMSession.PROTOCOL)).set(CIMSession.WEBSOCKET);

        SentBody body = new SentBody();
        body.setKey(CIMNioSocketAcceptor.WEBSOCKET_HANDLER_KEY);
        body.setTimestamp(System.currentTimeMillis());
        body.put("key", secKey);
        queue.add(body);

    } else {
        iobuffer.resetReaderIndex();
    }

    return handShake;
}

From source file:com.feihong.newzxclient.tcp.IntLengthDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    // Wait until the length prefix is available.
    if (in.readableBytes() < 4) {
        //String strError = String.format("Read length data error, in.readableBytes(): %d, length: %d", in.readableBytes(), 4);
        //writeLog(strError);
        return;//from  w w  w  . j  a  v  a 2s .  c  om
    }

    in.markReaderIndex();

    // Wait until the whole data is available.
    int dataLength = in.readInt();
    if (in.readableBytes() < dataLength) {
        //String strError = String.format("Read length data error, in.readableBytes(): %d, length: %d", in.readableBytes(), dataLength + 4);
        //writeLog(strError);

        in.resetReaderIndex();
        return;
    }

    // Convert the received data into a new BigInteger.
    byte[] decoded = new byte[dataLength];
    in.readBytes(decoded);

    try {
        Msg.CommonMessage commonMessage = Msg.CommonMessage.parseFrom(decoded);
        out.add(commonMessage);
    } catch (InvalidProtocolBufferException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.fjn.helper.frameworkex.netty.v4.echotest.EchoClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    System.out.println("Client received : " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes())));
    msg.release();/*from  w  w  w .java  2 s .c  o  m*/
}

From source file:com.flowpowered.network.pipeline.MessageProcessorDecoder.java

License:MIT License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> frames) throws Exception {
    MessageProcessor processor = getProcessor();
    if (processor == null) {
        frames.add(buf.readBytes(buf.readableBytes()));
        return;//w  w  w  . j av  a  2  s.  c  o  m
    }
    // Eventually, we will run out of bytes and a ReplayableError will be called
    ByteBuf liveBuffer = ctx.alloc().buffer();
    liveBuffer = processor.processInbound(ctx, buf, liveBuffer);
    frames.add(liveBuffer);
}

From source file:com.flowpowered.network.pipeline.MessageProcessorDecoderTest.java

License:MIT License

@Test
public void test() throws Exception {
    // Preprocessor basically is split into two parts
    // Part 1 is just a direct copy
    // Part 2 negates all bytes before copying
    final AtomicReference<MessageProcessor> processor = new AtomicReference<>();
    MessageProcessorDecoder processorDecoder = new MessageProcessorDecoder(null) {
        @Override/*  w w  w. j  a v  a2s.co m*/
        protected MessageProcessor getProcessor() {
            return processor.get();
        }
    };

    // Set up a fake ChannelHandlerContext
    FakeChannelHandlerContext fake = ChannelHandlerContextFaker.setup();
    AtomicReference<ByteBuf> ref = new AtomicReference<>();
    fake.setReference(ref);
    LinkedList<byte[]> outputList = new LinkedList<>();

    Random r = new Random();

    // Get some random bytes for data
    byte[] input = new byte[LENGTH];
    r.nextBytes(input);

    boolean breakOccured = false;
    int position = 0;

    for (int i = 0; i < input.length;) {
        // Simulate real data read
        int burstSize = r.nextInt(512);
        // With a 1/10 chance of having an extra-large burst
        if (r.nextInt(10) == 0) {
            burstSize *= 10;
        }

        // Final burst needs to be clamped
        if (i + burstSize > input.length) {
            burstSize = input.length - i;
        }

        // And we can't negate in the middle of a burst
        if (i + burstSize > BREAK && !breakOccured) {
            burstSize = BREAK - i;
        }

        // Write info to a new ByteBuf
        final ByteBuf buf = Unpooled.buffer(burstSize);
        buf.writeBytes(input, i, burstSize);
        i += burstSize;

        // Fake a read
        processorDecoder.channelRead(fake, buf);

        final ByteBuf returned = ref.get();

        while (returned != null) {
            int packetSize = r.nextInt(128) + 1;
            if (r.nextInt(10) == 0) {
                packetSize *= 20;
            }

            if (packetSize > returned.readableBytes()) {
                packetSize = returned.readableBytes();
            }
            if (position + packetSize > BREAK && !breakOccured) {
                packetSize = BREAK - position;
            }
            if (position + packetSize > LENGTH) {
                packetSize = LENGTH - position;
            }

            if (packetSize == 0) {
                break;
            }

            byte[] array = new byte[packetSize];

            returned.readBytes(array);
            position += packetSize;

            if (position == BREAK) {
                processor.set(new NegatingProcessor(512));
                breakOccured = true;
            }
            outputList.add(array);
        }
    }

    // Get the output data and combine into one array
    byte[] output = new byte[LENGTH];
    int i = 0;
    for (byte[] array : outputList) {
        for (int j = 0; j < array.length; j++) {
            output[i++] = array[j];
        }
    }

    for (i = 0; i < input.length; i++) {
        byte expected = i < BREAK ? input[i] : (byte) ~input[i];
        if (output[i] != expected) {
            for (int j = Math.max(0, i - 10); j <= i + 10; j++) {
                System.out.println(j + ") " + Integer.toBinaryString(j < BREAK ? input[j] : (byte) ~input[j])
                        + " " + Integer.toBinaryString(output[j]));
            }
        }

        if (i < BREAK) {
            assertTrue("Input/Output mismatch at position " + i + ". Expected " + input[i] + " but got "
                    + output[i] + ". Break is: " + BREAK, output[i] == input[i]);
        } else {
            assertTrue(
                    "Input/Output mismatch at position " + i + ", after the processor change. Expected "
                            + (byte) ~input[i] + " but got " + output[i] + ". Break is: " + BREAK,
                    output[i] == (byte) ~input[i]);
        }
    }
}

From source file:com.flowpowered.network.pipeline.MessageProcessorEncoder.java

License:MIT License

@Override
protected void encode(ChannelHandlerContext ctx, final ByteBuf buf, List<Object> out) throws Exception {
    final MessageProcessor processor = getProcessor();
    if (processor == null) {
        out.add(buf.readBytes(buf.readableBytes()));
        return;/*  w  ww.j ava 2  s .  c o  m*/
    }
    ByteBuf toAdd = ctx.alloc().buffer();
    toAdd = processor.processOutbound(ctx, buf, toAdd);
    out.add(toAdd);
}