Java Code Examples for io.netty.buffer.ByteBuf#readByte()

The following examples show how to use io.netty.buffer.ByteBuf#readByte() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Override
protected void readClientData(ByteBuf clientdata) {
	PositionSerializer.readPositionTo(clientdata, position);
	action = MiscSerializer.readVarIntEnum(clientdata, Action.CONSTANT_LOOKUP);
	mode = MiscSerializer.readVarIntEnum(clientdata, Mode.CONSTANT_LOOKUP);
	name = StringSerializer.readVarIntUTF8String(clientdata, Short.MAX_VALUE);
	offsetX = clientdata.readByte();
	offsetY = clientdata.readByte();
	offsetZ = clientdata.readByte();
	sizeX = clientdata.readByte();
	sizeY = clientdata.readByte();
	sizeZ = clientdata.readByte();
	mirror = MiscSerializer.readVarIntEnum(clientdata, Mirror.CONSTANT_LOOKUP);
	rotation = MiscSerializer.readVarIntEnum(clientdata, Rotation.CONSTANT_LOOKUP);
	metadata = StringSerializer.readVarIntUTF8String(clientdata, Short.MAX_VALUE);
	integrity = clientdata.readFloat();
	seed = VarNumberSerializer.readVarLong(clientdata);
	flags = clientdata.readByte();
}
 
Example 2
@Override
protected void read0(ByteBuf from) {
	this.name = StringSerializer.readShortUTF16BEString(from);
	this.mode = from.readByte();
	if ((this.mode == 0) || (this.mode == 2)) {
		this.displayName = StringSerializer.readShortUTF16BEString(from);
		this.prefix = StringSerializer.readShortUTF16BEString(from);
		this.suffix = StringSerializer.readShortUTF16BEString(from);
		this.friendlyFire = from.readByte();
	}
	if ((this.mode == 0) || (this.mode == 3) || (this.mode == 4)) {
		int len = from.readShort();
		this.players = new String[len];
		for (int i = 0; i < len; ++i) {
			this.players[i] = StringSerializer.readShortUTF16BEString(from);
		}
	}
}
 
Example 3
public static int readVarInt(ByteBuf input, int maxBytes)
{
    int out = 0;
    int bytes = 0;
    byte in;
    do {
        in = input.readByte();

        out |= (in & 0x7F) << (bytes++ * 7);

        if (bytes > maxBytes) {
            throw new RuntimeException("VarInt too big");
        }
    } while ((in & 0x80) == 0x80);

    return out;
}
 
Example 4
Source Project: fastjgame   File: AbstractSocketCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object byteBuf) throws Exception {
    ByteBuf msg = (ByteBuf) byteBuf;
    try {
        // 任何编解码出现问题都会在上层消息判断哪里出现问题,这里并不处理channel数据是否异常
        byte pkgTypeNumber = msg.readByte();
        NetMessageType netMessageType = NetMessageType.forNumber(pkgTypeNumber);
        if (null == netMessageType) {
            // 约定之外的包类型
            throw new IOException("Unknown pkgTypeNumber: " + pkgTypeNumber);
        }
        readMsg(ctx, netMessageType, msg);
    } finally {
        // 解码结束,释放资源
        msg.release();
    }
}
 
Example 5
Source Project: extract   File: ResultDecoder.java    License: MIT License 6 votes vote down vote up
@Override
public Object decode(final ByteBuf buffer, final State state) throws IOException {
	String result = new String (new char[] {(char) buffer.readByte()});
	ExtractionStatus extractionStatus = ExtractionStatus.parse(result);
	if (buffer.capacity() == 1) {
		return new Report(extractionStatus);
	} else {
		buffer.readByte(); // pipe char |
		ByteBuf exceptionPayload = buffer.getBytes(0, new byte[buffer.capacity() - 2]);
		try (ObjectInputStream objectInputStream = new ObjectInputStream(new ByteBufInputStream(exceptionPayload))) {
			Exception ex = (Exception) objectInputStream.readObject();
			return new Report(extractionStatus, ex);
		} catch (ClassNotFoundException e) {
			logger.warn("cannot read object : ", e);
			return new Report(extractionStatus);
		}
	}
}
 
Example 6
@Override
public void fromBytes(ByteBuf buf)
{
    try
    {
        this.windowId = buf.readByte();
        this.slotNum = buf.readShort();
        this.stack = ByteBufUtilsEU.readItemStackFromBuffer(buf);
    }
    catch (IOException e)
    {
        EnderUtilities.logger.warn("MessageSyncSlot: Exception while reading data from buffer", e);
    }
}
 
Example 7
Source Project: grpc-java   File: FakeChannelCrypter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void decrypt(ByteBuf out, ByteBuf tag, List<ByteBuf> ciphertext)
    throws GeneralSecurityException {
  checkState(!destroyCalled);
  for (ByteBuf buf : ciphertext) {
    out.writeBytes(buf);
  }
  while (tag.isReadable()) {
    if (tag.readByte() != TAG_BYTE) {
      throw new AEADBadTagException("Tag mismatch!");
    }
  }
}
 
Example 8
Source Project: jfxvnc   File: HextileDecoder.java    License: Apache License 2.0 5 votes vote down vote up
private static void readColor(ByteBuf in, byte[] buffer, int bytesPerPixel, int redPos, int bluePos) {
  if (bytesPerPixel == 1) {
    buffer[0] = in.readByte();
  } else {
    buffer[redPos] = in.readByte();
    buffer[1] = in.readByte();
    buffer[bluePos] = in.readByte();
    in.skipBytes(1);
  }

}
 
Example 9
Source Project: joyqueue   File: EndTxnCodec.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public EndTxnRequest decode(KafkaHeader header, ByteBuf buffer) throws Exception {
    String transactionId = Serializer.readString(buffer, Serializer.SHORT_SIZE);
    long producerId = buffer.readLong();
    short producerEpoch = buffer.readShort();
    boolean transactionResult = (buffer.readByte() == 1);

    EndTxnRequest endTxnRequest = new EndTxnRequest();
    endTxnRequest.setTransactionId(transactionId);
    endTxnRequest.setProducerId(producerId);
    endTxnRequest.setProducerEpoch(producerEpoch);
    endTxnRequest.setTransactionResult(transactionResult);
    return endTxnRequest;
}
 
Example 10
Source Project: fastjgame   File: AbstractSocketCodec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 心跳协议解码
 */
final SocketPingPongEvent readAckPingPongMessage(Channel channel, String sessionId, ByteBuf msg) {
    long ack = msg.readLong();
    if (msg.readByte() == 1) {
        return new SocketPingPongEvent(channel, sessionId, ack, PingPongMessage.PING);
    } else {
        return new SocketPingPongEvent(channel, sessionId, ack, PingPongMessage.PONG);
    }
}
 
Example 11
Source Project: turbo-rpc   File: TracerSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public final Tracer read(ByteBuf buffer) {
	byte flag = buffer.readByte();

	if (flag == 0) {
		return null;
	}

	Tracer tracer = new Tracer();

	if ((flag & TRACE_ID_FLAG) == TRACE_ID_FLAG) {
		tracer.setTraceId(new ObjectId(buffer));
	}

	if ((flag & SPAN_ID_FLAG) == SPAN_ID_FLAG) {
		tracer.setSpanId(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & PARENT_ID_FLAG) == PARENT_ID_FLAG) {
		tracer.setParentId(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & CS_FLAG) == CS_FLAG) {
		tracer.setCs(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & CR_FLAG) == CR_FLAG) {
		tracer.setCr(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & SS_FLAG) == SS_FLAG) {
		tracer.setSs(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & SR_FLAG) == SR_FLAG) {
		tracer.setSr(ByteBufUtils.readVarLong(buffer));
	}

	return tracer;
}
 
Example 12
Source Project: Almost-Famous   File: Misc.java    License: MIT License 5 votes vote down vote up
public static long toLong(ByteBuf in) {
    if (in.readableBytes() < 8) {
        throw new CorruptedFrameException("to long.");
    }
    return ((in.readByte() & 0xff) << 56) | ((in.readByte() & 0xff) << 48) | ((in.readByte() & 0xff) << 40)
            | ((in.readByte() & 0xff) << 32) | ((in.readByte() & 0xff) << 24) | ((in.readByte() & 0xff) << 16)
            | ((in.readByte() & 0xff) << 8) | ((in.readByte() & 0xff) << 0);
}
 
Example 13
@Override
public Notification parseMessage(final ByteBuf buffer, final PeerSpecificParserConstraint constraint)
        throws BGPDocumentedException, BGPParsingException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(), "Array of bytes cannot be null or empty.");
    Preconditions.checkArgument(buffer.readableBytes() >= MessageUtil.COMMON_HEADER_LENGTH,
            "Too few bytes in passed array. Passed: %s. Expected: >= %s.", buffer.readableBytes(),
            MessageUtil.COMMON_HEADER_LENGTH);
    final byte[] marker = ByteArray.readBytes(buffer, MessageUtil.MARKER_LENGTH);

    if (!Arrays.equals(marker, MARKER)) {
        throw new BGPDocumentedException("Marker not set to ones.", BGPError.CONNECTION_NOT_SYNC);
    }
    final int messageLength = buffer.readUnsignedShort();
    // to be sent with Error message
    final byte typeBytes = buffer.readByte();
    final int messageType = UnsignedBytes.toInt(typeBytes);

    if (messageLength < MessageUtil.COMMON_HEADER_LENGTH) {
        throw BGPDocumentedException.badMessageLength("Message length field not within valid range.",
            messageLength);
    }

    if (messageLength - MessageUtil.COMMON_HEADER_LENGTH != buffer.readableBytes()) {
        throw new BGPParsingException("Size doesn't match size specified in header. Passed: "
                + buffer.readableBytes() + "; Expected: " + (messageLength - MessageUtil.COMMON_HEADER_LENGTH)
                + ". ");
    }

    final ByteBuf msgBody = buffer.readSlice(messageLength - MessageUtil.COMMON_HEADER_LENGTH);

    final Notification msg = parseBody(messageType, msgBody, messageLength, constraint);
    if (msg == null) {
        throw new BGPDocumentedException("Unhandled message type " + messageType, BGPError.BAD_MSG_TYPE,
            new byte[] { typeBytes });
    }
    return msg;
}
 
Example 14
Source Project: catalyst   File: NettyHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext context, Object message) {
  ByteBuf buffer = (ByteBuf) message;
  int type = buffer.readByte();
  switch (type) {
    case NettyConnection.REQUEST:
      handleRequest(buffer, context);
      break;
    case NettyConnection.RESPONSE:
      handleResponse(buffer, context);
      break;
  }
}
 
Example 15
public static Object getFluidOrItemStack(ByteBuf buf){
    if(buf.readByte() == 0) {
        return ByteBufUtils.readItemStack(buf);
    } else {
        return new FluidStack(FluidRegistry.getFluid(ByteBufUtils.readUTF8String(buf)), buf.readInt(), ByteBufUtils.readTag(buf));
    }
}
 
Example 16
/**
 * 处理接收到的数据,转化为 Message 并送入下一级处理器
 *
 * @param ctx 处理器上下文
 * @param msg 待处理的已接收数据
 */

private void processByteBuf(ChannelHandlerContext ctx, ByteBuf msg) {
    while (msg.readableBytes() >= 13) {
        msg.skipBytes(2);
        int msgId = msg.readByte();
        int deviceId = msg.readByte();
        int groupId = msg.readByte();
        IMessage message = handleMessage(msgId, deviceId, groupId, msg);
        ctx.fireChannelRead(message);
    }
}
 
Example 17
Source Project: ViaVersion   File: Chunk1_9_1_2Type.java    License: MIT License 4 votes vote down vote up
@Override
public Chunk read(ByteBuf input, ClientWorld world) throws Exception {
    boolean replacePistons = world.getUser().getProtocolInfo().getPipeline().contains(Protocol1_10To1_9_3_4.class) && Via.getConfig().isReplacePistons();
    int replacementId = Via.getConfig().getPistonReplacementId();

    int chunkX = input.readInt();
    int chunkZ = input.readInt();

    boolean groundUp = input.readBoolean();
    int primaryBitmask = Type.VAR_INT.readPrimitive(input);
    // Size (unused)
    Type.VAR_INT.readPrimitive(input);

    BitSet usedSections = new BitSet(16);
    ChunkSection[] sections = new ChunkSection[16];
    // Calculate section count from bitmask
    for (int i = 0; i < 16; i++) {
        if ((primaryBitmask & (1 << i)) != 0) {
            usedSections.set(i);
        }
    }

    // Read sections
    for (int i = 0; i < 16; i++) {
        if (!usedSections.get(i)) continue; // Section not set
        ChunkSection section = Types1_9.CHUNK_SECTION.read(input);
        sections[i] = section;
        section.readBlockLight(input);
        if (world.getEnvironment() == Environment.NORMAL) {
            section.readSkyLight(input);
        }
        if (replacePistons) {
            section.replacePaletteEntry(36, replacementId);
        }
    }

    int[] biomeData = groundUp ? new int[256] : null;
    if (groundUp) {
        for (int i = 0; i < 256; i++) {
            biomeData[i] = input.readByte() & 0xFF;
        }
    }

    return new BaseChunk(chunkX, chunkZ, groundUp, false, primaryBitmask, sections, biomeData, new ArrayList<CompoundTag>());
}
 
Example 18
Source Project: azure-cosmosdb-java   File: RntbdTokenType.java    License: MIT License 4 votes vote down vote up
@Override
public final Object read(final ByteBuf in) {
    return in.readByte();
}
 
Example 19
Source Project: Protocol   File: BedrockUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static float readByteAngle(ByteBuf buffer) {
    Preconditions.checkNotNull(buffer, "buffer");
    return buffer.readByte() * (360f / 256f);
}
 
Example 20
Source Project: archimedes-ships   File: ASMessagePipeline.java    License: MIT License 4 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception
{
	ByteBuf payload = msg.payload();
	byte discriminator = payload.readByte();
	Class<? extends ASMessage> clazz = packets.get(discriminator);
	if (clazz == null)
	{
		throw new NullPointerException("No packet registered for discriminator: " + discriminator);
	}
	
	EntityPlayer player = null;
	Side side = FMLCommonHandler.instance().getEffectiveSide();
	switch (side)
	{
	case CLIENT:
		player = getClientPlayer();
		break;
	case SERVER:
		INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
		player = ((NetHandlerPlayServer) netHandler).playerEntity;
		break;
	default:
	}
	
	ASMessage pkt = clazz.newInstance();
	try
	{
		pkt.decodeInto(ctx, payload.slice(), player);
	} catch (IOException e)
	{
		e.printStackTrace();
		throw e;
	}
	
	switch (side)
	{
	case CLIENT:
		pkt.handleClientSide(player);
		break;
	case SERVER:
		pkt.handleServerSide(player);
		break;
	default:
	}
	
	out.add(pkt);
}