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.necla.simba.server.gateway.server.frontend.FrontendFrameEncoder.java

License:Apache License

private void compress(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) {
    LOG.debug("compress here");
    byte[] inAry = new byte[msg.readableBytes()];
    msg.readBytes(inAry);
    int sizeEstimate = (int) Math.ceil(inAry.length * 1.001) + 12 + 4;
    LOG.debug("compress here2");

    out.ensureWritable(sizeEstimate);// w  w w. j  a  v a2 s. c o  m

    int beginIndex = out.writerIndex();

    out.writerIndex(beginIndex + 4);

    try {

        deflater.setInput(inAry);

        while (!deflater.needsInput()) {
            LOG.debug("compress here3333");

            int numBytes = deflater.deflate(encodeBuf, 0, encodeBuf.length);
            LOG.debug("Compressed numBytes=" + numBytes);
            out.writeBytes(encodeBuf, 0, numBytes);
            LOG.debug("compress here4");

        }

        deflater.finish();
        while (!deflater.finished()) {
            int numBytes = deflater.deflate(encodeBuf, 0, encodeBuf.length);
            out.writeBytes(encodeBuf, 0, numBytes);
            LOG.debug("compress here5");

        }
        deflater.reset();
        int len = out.writerIndex() - beginIndex - 4;

        Stats.sent(out.writerIndex() + beginIndex + 4);

        LOG.debug("Compressed len=" + len);
        len |= (1 << 30);
        out.setInt(beginIndex, len);
    } catch (Exception e) {
        LOG.debug("Exception" + e);
    }
}

From source file:com.net.ServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    System.out.println("nodedataService");
    ByteBuf buf = (ByteBuf) msg;
    byte[] req = new byte[buf.readableBytes()];
    buf.readBytes(req);
    System.out.println(/* ww  w.java  2  s  .  c o m*/
            DateUtils.getDateTime() + "++" + req[0] + "+" + req[1] + (req[0] == -21 && req[1] == -112));
    NetUtil.print16String(req);
    if (req[0] == -21 && req[1] == 96) {//"EB 60" 
        //2? ?ID??
        byte[] segment = new byte[4];
        segment[0] = 0;
        segment[1] = 0;
        segment[2] = req[2];
        segment[3] = req[3];
        byte[] id = new byte[4];
        id[0] = 0;
        id[1] = 0;
        id[2] = req[4];
        id[3] = req[5];
        String nodeid = NetUtil.bytesToInt(segment) + "_" + NetUtil.bytesToInt(id);
        this.setNodeId(nodeid);
        //          bs[8] = req[2];
        //          bs[9] = req[3];
        //          bs[10] = req[4];
        //          bs[11] = req[5];
        //          bs[20] = (byte) (NetUtil.bytesToInt(req[2])+NetUtil.bytesToInt(req[3])+NetUtil.bytesToInt(req[4])+NetUtil.bytesToInt(req[5]));
        //         ByteBuf resp = Unpooled.copiedBuffer(bs);
        byte[] bb = (byte[]) JedisUtils.getObject(ZTConstants.jedisKey.send_data_byte + nodeid);
        ByteBuf resp = Unpooled.copiedBuffer(bb);
        ctx.write(resp);
    } else if (req[0] == -21 && req[1] == -112) {//"EB 90" ??

        byte[] segment = new byte[4];
        segment[3] = 0;
        segment[2] = 0;
        segment[1] = req[2];
        segment[0] = req[3];
        byte[] id = new byte[4];
        id[3] = 0;
        id[2] = 0;
        id[1] = req[40];
        id[0] = req[41];
        String data_nodeid = NetUtil.bytesToInt(segment) + "_" + NetUtil.bytesToInt(id);
        /*if(nodeId == null){
           redisTemplate.convertAndSend(ZTConstants.channel.dataLog, ZTConstants.resultCode.noNodeId+":"+nodeId);
        }
        if(!data_nodeid.equals(nodeId)){
           redisTemplate.convertAndSend(ZTConstants.channel.dataLog, ZTConstants.resultCode.nodeIdError+":"+nodeId);
        }*/
        System.out.println("");
        redisTemplate.convertAndSend(ZTConstants.channel.reciveData, req);

    } else if (req[0] == 81) {//4???51??
        redisTemplate.convertAndSend(ZTConstants.channel.dataLog,
                ZTConstants.resultCode.success + ":" + nodeId);
    }
}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyBackendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    ByteBuf buf = (ByteBuf) msg;
    System.out.println("channelRead:" + ByteBufUtil.hexDump((buf)));
    while (buf.readableBytes() > 0) {

        int payload = buf.readUnsignedMedium();
        int frameType = buf.readByte();
        Http2Flags flags = new Http2Flags(buf.readUnsignedByte());
        int streamId = readUnsignedInt(buf);
        ByteBuf payloadBuf = buf.readBytes(payload);
        ByteBuf copy = ctx.alloc().buffer();
        System.out.println("frame_type:" + frameType + "," + ByteBufUtil.hexDump((payloadBuf)));
        switch (frameType) {
        case Http2FrameTypes.SETTINGS:
            handleSettingFrame(ctx, flags);
            break;
        case Http2FrameTypes.WINDOW_UPDATE:
            handleWindowsUpdateFrame(ctx);
            break;
        case Http2FrameTypes.HEADERS:

            copy.writeMedium(payload);/*from w w w . ja v  a 2s .co  m*/
            copy.writeByte(frameType);
            copy.writeByte(flags.value());
            copy.writeInt(streamId);
            copy.writeBytes(payloadBuf);
            forward(ctx, copy);
            break;
        case Http2FrameTypes.DATA:
            copy.writeMedium(payload);
            copy.writeByte(frameType);
            copy.writeByte(flags.value());
            copy.writeInt(streamId);
            copy.writeBytes(payloadBuf);
            forward(ctx, copy);
            break;
        default:
            break;

        }
    }

}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyFrontendHandler.java

License:Apache License

private void readFrame(final ChannelHandlerContext ctx, ByteBuf buf) {
    if (first) {/*from w  w w . jav  a  2 s  .  co  m*/
        try {
            readClientPrefaceString(buf);
        } catch (Http2Exception e) {
            e.printStackTrace();
        }
        first = false;
    }

    while (buf.readableBytes() > 0) {

        int payload = buf.readUnsignedMedium();
        int frameType = buf.readByte();
        Http2Flags flags = new Http2Flags(buf.readUnsignedByte());
        int streamId = readUnsignedInt(buf);
        ByteBuf payloadBuf = buf.readBytes(payload);
        ByteBuf copy = ctx.alloc().buffer();
        switch (frameType) {
        case Http2FrameTypes.SETTINGS:
            handleSettingFrame(ctx, flags);
            break;
        case Http2FrameTypes.WINDOW_UPDATE:
            handleWindowsUpdateFrame(ctx);
            break;
        case Http2FrameTypes.HEADERS:

            copy.writeMedium(payload);
            copy.writeByte(frameType);
            copy.writeByte(flags.value());
            copy.writeInt(streamId);
            copy.writeBytes(payloadBuf);
            handleHeaderFrame(ctx, copy, streamId);
            break;
        case Http2FrameTypes.DATA:
            copy.writeMedium(payload);
            copy.writeByte(frameType);
            copy.writeByte(flags.value());
            copy.writeInt(streamId);
            copy.writeBytes(payloadBuf);
            handleDataFrame(ctx, copy, streamId);
            break;
        default:
            break;

        }
    }
}

From source file:com.newlandframework.avatarmq.netty.MessageObjectDecoder.java

License:Apache License

protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if (in.readableBytes() < MessageObjectDecoder.MESSAGE_LENGTH) {
        return;/*ww w  .  j  a v  a  2 s.co  m*/
    }

    in.markReaderIndex();
    int messageLength = in.readInt();

    if (messageLength < 0) {
        ctx.close();
    }

    if (in.readableBytes() < messageLength) {
        in.resetReaderIndex();
        return;
    } else {
        byte[] messageBody = new byte[messageLength];
        in.readBytes(messageBody);

        try {
            Object obj = util.decode(messageBody);
            out.add(obj);
        } catch (IOException ex) {
            Logger.getLogger(MessageObjectDecoder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.newlandframework.rpc.serialize.MessageDecoder.java

License:Apache License

protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if (in.readableBytes() < MessageDecoder.MESSAGE_LENGTH) {
        return;/* ww w . jav  a 2 s  .c  o m*/
    }

    in.markReaderIndex();
    int messageLength = in.readInt();

    if (messageLength < 0) {
        ctx.close();
    }

    if (in.readableBytes() < messageLength) {
        in.resetReaderIndex();
        return;
    } else {
        byte[] messageBody = new byte[messageLength];
        in.readBytes(messageBody);

        try {
            Object obj = util.decode(messageBody);
            out.add(obj);
        } catch (IOException ex) {
            Logger.getLogger(MessageDecoder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.noahkurrack.onenine.network.MessageSingleParticleEvent.java

License:Open Source License

@Override
public void fromBytes(ByteBuf buf) {

    int particleNameLength = buf.readInt();
    this.particleName = new String(buf.readBytes(particleNameLength).array());
    this.xCoord = buf.readDouble();
    this.yCoord = buf.readDouble();
    this.zCoord = buf.readDouble();
    this.xVelocity = buf.readDouble();
    this.yVelocity = buf.readDouble();
    this.zVelocity = buf.readDouble();

}

From source file:com.ns.netty.gcd.server.BigIntegerDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {

    System.out.println("Decoder received event");

    // Wait until the length prefix is available.
    if (in.readableBytes() < 5) {
        return;// w w  w.j  a  v  a2  s .c  o  m
    }

    in.markReaderIndex();

    // Check the magic number.
    int magicNumber = in.readUnsignedByte();
    if (magicNumber != 'F') {
        in.resetReaderIndex();
        throw new CorruptedFrameException("Invalid magic number: " + magicNumber);
    }

    // Wait until the whole data is available.
    int dataLength = in.readInt();
    if (in.readableBytes() < dataLength) {
        in.resetReaderIndex();
        return;
    }

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

    out.add(new BigInteger(decoded));
}

From source file:com.ogarproject.ogar.server.net.packet.universal.PacketOMPMessage.java

License:Open Source License

@Override
public void readData(ByteBuf buf) {
    channel = readUTF8(buf);/*  w w w  . j a  va2 s.com*/
    int size = buf.readableBytes();
    if (size > 32767) {
        throw new MalformedPacketException("Exceeded max OMP message size (" + size + " > 32767)");
    }

    data = new byte[size];
    buf.readBytes(data);
}

From source file:com.openddal.server.mysql.MySQLAuthenticator.java

License:Apache License

@Override
public void authorize(Channel channel, ByteBuf buf) {
    MySQLSession session = channel.attr(TMP_SESSION_KEY).getAndRemove();
    HandshakeResponse authReply = null;/*from w w w . ja v a2s  .com*/
    try {
        byte[] packet = new byte[buf.readableBytes()];
        buf.readBytes(packet);
        authReply = HandshakeResponse.loadFromPacket(packet);
        Connection connect = connectEngine(authReply);
        session.setHandshakeResponse(authReply);
        session.setEngineConnection(connect);
        session.bind(channel);
        success(channel);
    } catch (Exception e) {
        String msg = authReply == null ? e.getMessage()
                : "Access denied for user '" + authReply.username + "' to database '" + authReply.schema + "'";
        LOGGER.error("Authorize failed. " + msg, e);
        error(channel, MySQLErrorCode.ER_DBACCESS_DENIED_ERROR, msg);
    } finally {
        buf.release();
    }
}