Java Code Examples for io.netty.buffer.ByteBuf.readableBytes()

The following are Jave code examples for showing how to use readableBytes() of the io.netty.buffer.ByteBuf class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: azeroth   File: ReplierSupport.java   Source Code and License Vote up 6 votes
private void readHead(ByteBuf in) {
    if (in.readableBytes() < FastdfsConstants.FDFS_HEAD_LEN) {
        return;
    }
    length = in.readLong();
    byte cmd = in.readByte();
    byte errno = in.readByte();
    if (errno != 0) {
        throw new FastdfsException("Fastdfs responsed with an error, errno is " + errno);
    }
    if (cmd != RESP) {
        throw new FastdfsException("Expect response command code error : " + cmd);
    }
    long expectLength = expectLength();
    if (expectLength >= 0 && length != expectLength) {
        throw new FastdfsException(
            "Expect response length : " + expectLength + " , but reply length : " + length);
    }
    atHead = false;
}
 
Example 2
Project: buddha   File: RpcResponseCodec.java   Source Code and License Vote up 6 votes
@Override
protected void decode(ChannelHandlerContext context, ByteBuf byteBuf, List<Object> list)
        throws Exception {
    if (byteBuf.readableBytes() < 4) {
        return;
    }
    int len = byteBuf.readInt();
    if (byteBuf.readableBytes() < len) {
        throw new RuntimeException("Insufficient bytes to be read, expected: " + len);
    }
    byte[] bytes = new byte[len];
    byteBuf.readBytes(bytes);
    Serializer serializer = SerializerFactory.load();
    Object object = serializer.deserialize(bytes, RpcResponse.class);
    list.add(object);
}
 
Example 3
Project: elephant   File: NettyDecoder.java   Source Code and License Vote up 6 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
		List<Object> out) throws Exception {
	//获取消息头所标识的消息体字节数组长度
       if (in.readableBytes() < 4) {
           return;
       }
       in.markReaderIndex();
       int dataLength = in.readInt();
       if (dataLength < 0) {
           ctx.close();
       }
       //若当前可以获取到的字节数小于实际长度,则直接返回,直到当前可以获取到的字节数等于实际长度
       if (in.readableBytes() < dataLength) {
           in.resetReaderIndex();
           return;
       }
       //读取完整的消息体字节数组
       byte[] data = new byte[dataLength];
       in.readBytes(data);

       //将字节数组反序列化为java对象(SerializerEngine参考序列化与反序列化章节)
       Object obj = SerializerEngine.deserialize(data, genericClass, serializeType.getCode());
       out.add(obj);
}
 
Example 4
Project: DecompiledMinecraft   File: MessageSerializer2.java   Source Code and License Vote up 6 votes
protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception
{
    int i = p_encode_2_.readableBytes();
    int j = PacketBuffer.getVarIntSize(i);

    if (j > 3)
    {
        throw new IllegalArgumentException("unable to fit " + i + " into " + 3);
    }
    else
    {
        PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_);
        packetbuffer.ensureWritable(j + i);
        packetbuffer.writeVarIntToBuffer(i);
        packetbuffer.writeBytes(p_encode_2_, p_encode_2_.readerIndex(), i);
    }
}
 
Example 5
Project: Backmemed   File: NettyPacketDecoder.java   Source Code and License Vote up 5 votes
protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List<Object> p_decode_3_) throws IOException, InstantiationException, IllegalAccessException, Exception
{
    if (p_decode_2_.readableBytes() != 0)
    {
        PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_);
        int i = packetbuffer.readVarIntFromBuffer();
        Packet<?> packet = ((EnumConnectionState)p_decode_1_.channel().attr(NetworkManager.PROTOCOL_ATTRIBUTE_KEY).get()).getPacket(this.direction, i);

        if (packet == null)
        {
            throw new IOException("Bad packet id " + i);
        }
        else
        {
            packet.readPacketData(packetbuffer);

            if (packetbuffer.readableBytes() > 0)
            {
                throw new IOException("Packet " + ((EnumConnectionState)p_decode_1_.channel().attr(NetworkManager.PROTOCOL_ATTRIBUTE_KEY).get()).getId() + "/" + i + " (" + packet.getClass().getSimpleName() + ") was larger than I expected, found " + packetbuffer.readableBytes() + " bytes extra whilst reading packet " + i);
            }
            else
            {
                p_decode_3_.add(packet);

                if (LOGGER.isDebugEnabled())
                {
                    LOGGER.debug(RECEIVED_PACKET_MARKER, " IN: [{}:{}] {}", new Object[] {p_decode_1_.channel().attr(NetworkManager.PROTOCOL_ATTRIBUTE_KEY).get(), Integer.valueOf(i), packet.getClass().getName()});
                }
            }
        }
    }
}
 
Example 6
Project: AgentX   File: Tcp2UdpHandler.java   Source Code and License Vote up 5 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    Channel udpChannel = XChannelMapper.getUdpChannel(udpSource);
    if (udpChannel == null) {
        log.warn("Bad Connection! (udp channel closed)");
        XChannelMapper.closeChannelGracefullyByTcpChannel(ctx.channel());
    } else if (udpChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                bytes = wrapper.unwrap(bytes);
                XRequest request = requestResolver.parse(bytes);
                String host = request.getHost();
                int port = request.getPort();
                byte[] content = Arrays.copyOfRange(bytes, bytes.length - request.getSubsequentDataLength(), bytes.length);
                log.info("\t          Proxy << Target \tFrom   {}:{}", host, port);

                // redirect tcp -> udp
                udpChannel.writeAndFlush(new DatagramPacket(Unpooled.wrappedBuffer(content), udpSource, new InetSocketAddress(host, port)));
                log.info("\tClient << Proxy           \tGet [{} bytes]", content.length);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 7
Project: FlexMC   File: MessageSplitter.java   Source Code and License Vote up 5 votes
@Override
protected void decode( ChannelHandlerContext channelHandlerContext, ByteBuf input, List<Object> output ) throws Exception {
    input.markReaderIndex();

    byte[] bytes = new byte[3];
    for ( int i = 0; i < bytes.length; i++ ) {
        if ( !input.isReadable() ) {
            input.resetReaderIndex();
            return;
        }
        bytes[i] = input.readByte();
        if ( bytes[i] >= 0 ) {
            ByteBuf buf = Unpooled.wrappedBuffer( bytes );
            try {
                int j = Message.readVarInt( buf );
                if ( input.readableBytes() < j ) {
                    input.resetReaderIndex();
                    return;
                }
                output.add( input.readBytes( j ) );
                return;
            } finally {
                buf.release();
            }
        }
    }
    throw new CorruptedFrameException( "length wider than 21-bit" );
}
 
Example 8
Project: Backmemed   File: NettyEncryptionTranslator.java   Source Code and License Vote up 5 votes
protected void cipher(ByteBuf in, ByteBuf out) throws ShortBufferException
{
    int i = in.readableBytes();
    byte[] abyte = this.bufToBytes(in);
    int j = this.cipher.getOutputSize(i);

    if (this.outputBuffer.length < j)
    {
        this.outputBuffer = new byte[j];
    }

    out.writeBytes((byte[])this.outputBuffer, 0, this.cipher.update(abyte, 0, i, this.outputBuffer));
}
 
Example 9
Project: L2J-Global   File: LengthFieldBasedFrameEncoder.java   Source Code and License Vote up 5 votes
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
{
	final ByteBuf buf = ctx.alloc().buffer(2);
	final short length = (short) (msg.readableBytes() + 2);
	buf.writeShort(buf.order() != ByteOrder.LITTLE_ENDIAN ? Short.reverseBytes(length) : length);
	out.add(buf);
	out.add(msg.retain());
}
 
Example 10
Project: nearenough   File: RtMessage.java   Source Code and License Vote up 5 votes
private Map<RtTag, byte[]> extractSingleMapping(ByteBuf msg) {
  long uintTag = msg.readUnsignedInt();
  RtTag tag = RtTag.fromUnsignedInt((int) uintTag);

  byte[] value = new byte[msg.readableBytes()];
  msg.readBytes(value);

  return Collections.singletonMap(tag, value);
}
 
Example 11
Project: lionrpc   File: MessageDecoder.java   Source Code and License Vote up 5 votes
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {

        if(in.readableBytes() < 4){
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if(in.readableBytes() < dataLength){
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        
        Kryo kryo = null;
        try{
	        kryo = pool.borrow();
	        Input input = new Input(data);
	        Object obj = kryo.readObject(input,this.clazz);
	        out.add(obj);
        }catch(Exception e){
        	LOG.warn("MessageDecoder happen exception.",e);
        }finally{
        	if(kryo != null){
        		pool.release(kryo);
        	}
        }
    }
 
Example 12
Project: CustomWorldGen   File: NettyPacketDecoder.java   Source Code and License Vote up 5 votes
protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List<Object> p_decode_3_) throws IOException, InstantiationException, IllegalAccessException, Exception
{
    if (p_decode_2_.readableBytes() != 0)
    {
        PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_);
        int i = packetbuffer.readVarIntFromBuffer();
        Packet<?> packet = ((EnumConnectionState)p_decode_1_.channel().attr(NetworkManager.PROTOCOL_ATTRIBUTE_KEY).get()).getPacket(this.direction, i);

        if (packet == null)
        {
            throw new IOException("Bad packet id " + i);
        }
        else
        {
            packet.readPacketData(packetbuffer);

            if (packetbuffer.readableBytes() > 0)
            {
                throw new IOException("Packet " + ((EnumConnectionState)p_decode_1_.channel().attr(NetworkManager.PROTOCOL_ATTRIBUTE_KEY).get()).getId() + "/" + i + " (" + packet.getClass().getSimpleName() + ") was larger than I expected, found " + packetbuffer.readableBytes() + " bytes extra whilst reading packet " + i);
            }
            else
            {
                p_decode_3_.add(packet);

                if (LOGGER.isDebugEnabled())
                {
                    LOGGER.debug(RECEIVED_PACKET_MARKER, " IN: [{}:{}] {}", new Object[] {p_decode_1_.channel().attr(NetworkManager.PROTOCOL_ATTRIBUTE_KEY).get(), Integer.valueOf(i), packet.getClass().getName()});
                }
            }
        }
    }
}
 
Example 13
Project: tasfe-framework   File: HttpContentInputStream.java   Source Code and License Vote up 5 votes
@Override
public int read(byte[] b, int off, int len) throws IOException {
    checkNotNull(b);
    if (0 == len) {
        return 0;
    }
    poll();
    if (isFinished()) {
        return -1;
    }
    ByteBuf byteBuf = readContent(len);
    int readableBytes = byteBuf.readableBytes();
    byteBuf.readBytes(b, off, readableBytes);
    return readableBytes - byteBuf.readableBytes();
}
 
Example 14
Project: BaseClient   File: NettyCompressionEncoder.java   Source Code and License Vote up 5 votes
protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception
{
    int i = p_encode_2_.readableBytes();
    PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_);

    if (i < this.treshold)
    {
        packetbuffer.writeVarIntToBuffer(0);
        packetbuffer.writeBytes(p_encode_2_);
    }
    else
    {
        byte[] abyte = new byte[i];
        p_encode_2_.readBytes(abyte);
        packetbuffer.writeVarIntToBuffer(abyte.length);
        this.deflater.setInput(abyte, 0, i);
        this.deflater.finish();

        while (!this.deflater.finished())
        {
            int j = this.deflater.deflate(this.buffer);
            packetbuffer.writeBytes((byte[])this.buffer, 0, j);
        }

        this.deflater.reset();
    }
}
 
Example 15
Project: CustomWorldGen   File: NettyCompressionEncoder.java   Source Code and License Vote up 5 votes
protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception
{
    int i = p_encode_2_.readableBytes();
    PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_);

    if (i < this.threshold)
    {
        packetbuffer.writeVarIntToBuffer(0);
        packetbuffer.writeBytes(p_encode_2_);
    }
    else
    {
        byte[] abyte = new byte[i];
        p_encode_2_.readBytes(abyte);
        packetbuffer.writeVarIntToBuffer(abyte.length);
        this.deflater.setInput(abyte, 0, i);
        this.deflater.finish();

        while (!this.deflater.finished())
        {
            int j = this.deflater.deflate(this.buffer);
            packetbuffer.writeBytes((byte[])this.buffer, 0, j);
        }

        this.deflater.reset();
    }
}
 
Example 16
Project: ClusterDeviceControlPlatform   File: ParsedMessageInBoundHandler.java   Source Code and License Vote up 5 votes
@Override
protected void channelRead0(ChannelHandlerContext ctx, FrameMajor msg) throws Exception {
    FrameMajorHeader head = msg.getHead();
    ByteBuf byteBuf = msg.getData();
    while (byteBuf.readableBytes() >= FrameSetting.SUB_FRAME_HEAD_LENGTH) {
        int subMsgId = byteBuf.readByte() & 0xFF;
        byte[] data = new byte[byteBuf.readShort()];
        byteBuf.readBytes(data);
        server.decodeAndHuntMessage(head, subMsgId, data, ctx.channel());
    }
}
 
Example 17
Project: BaseClient   File: MessageDeserializer.java   Source Code and License Vote up 5 votes
protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List<Object> p_decode_3_) throws IOException, InstantiationException, IllegalAccessException, Exception
{
    if (p_decode_2_.readableBytes() != 0)
    {
        PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_);
        int i = packetbuffer.readVarIntFromBuffer();
        Packet packet = ((EnumConnectionState)p_decode_1_.channel().attr(NetworkManager.attrKeyConnectionState).get()).getPacket(this.direction, i);

        if (packet == null)
        {
            throw new IOException("Bad packet id " + i);
        }
        else
        {
            packet.readPacketData(packetbuffer);

            if (packetbuffer.readableBytes() > 0)
            {
                throw new IOException("Packet " + ((EnumConnectionState)p_decode_1_.channel().attr(NetworkManager.attrKeyConnectionState).get()).getId() + "/" + i + " (" + packet.getClass().getSimpleName() + ") was larger than I expected, found " + packetbuffer.readableBytes() + " bytes extra whilst reading packet " + i);
            }
            else
            {
                p_decode_3_.add(packet);

                if (logger.isDebugEnabled())
                {
                    logger.debug(RECEIVED_PACKET_MARKER, " IN: [{}:{}] {}", new Object[] {p_decode_1_.channel().attr(NetworkManager.attrKeyConnectionState).get(), Integer.valueOf(i), packet.getClass().getName()});
                }
            }
        }
    }
}
 
Example 18
Project: Mods   File: TF2Message.java   Source Code and License Vote up 4 votes
@Override
public void fromBytes(ByteBuf buf) {
	//System.out.println("Read bytes: "+buf.readableBytes());
	this.bytes=new byte[buf.readableBytes()];
	buf.readBytes(this.bytes);
}
 
Example 19
Project: simulacron   File: ByteBufCodec.java   Source Code and License Vote up 4 votes
@Override
public int sizeOf(ByteBuf toMeasure) {
  return toMeasure.readableBytes();
}
 
Example 20
Project: CoreX   File: SessionManager.java   Source Code and License Vote up 4 votes
private boolean receivePacket() throws Exception {
    DatagramPacket datagramPacket = this.socket.readPacket();
    if (datagramPacket != null) {
        // Check this early
        try {
            String source = datagramPacket.sender().getHostString();
            currentSource = source; //in order to block address
            if (this.block.containsKey(source)) {
                return true;
            }

            if (this.ipSec.containsKey(source)) {
                this.ipSec.put(source, this.ipSec.get(source) + 1);
            } else {
                this.ipSec.put(source, 1);
            }

            ByteBuf byteBuf = datagramPacket.content();
            if (byteBuf.readableBytes() == 0) {
                // Exit early to process another packet
                return true;
            }
            byte[] buffer = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(buffer);
            int len = buffer.length;
            int port = datagramPacket.sender().getPort();

            this.receiveBytes += len;

            byte pid = buffer[0];

            if (pid == UNCONNECTED_PONG.ID) {
                return false;
            }

            Packet packet = this.getPacketFromPool(pid);
            if (packet != null) {
                packet.buffer = buffer;
                this.getSession(source, port).handlePacket(packet);
                return true;
            } else if (pid == UNCONNECTED_PING.ID) {
                packet = new UNCONNECTED_PING();
                packet.buffer = buffer;
                packet.decode();

                UNCONNECTED_PONG pk = new UNCONNECTED_PONG();
                pk.serverID = this.getID();
                pk.pingID = ((UNCONNECTED_PING) packet).pingID;
                pk.serverName = this.getName();
                this.sendPacket(pk, source, port);
            } else if (buffer.length != 0) {
                this.streamRAW(source, port, buffer);
                return true;
            } else {
                return false;
            }
        } finally {
            datagramPacket.release();
        }
    }

    return false;
}