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

The following are Jave code examples for showing how to use readShort() 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: ClusterDeviceControlPlatform   File: FrameRecognitionInBoundHandler.java   Source Code and License Vote up 6 votes
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
    while (true) {
        if (byteBuf.readableBytes() < FrameSetting.FRAME_HEAD_LENGTH) {
            return;
        }
        if (byteBuf.readByte() != FrameSetting.MAJOR_FRAME_HEAD_1
                || byteBuf.readByte() != FrameSetting.MAJOR_FRAME_HEAD_2) {
            return;
        }
        int groupId = byteBuf.readByte() & 0xFF;
        int msgId = byteBuf.readByte() & 0xFF;
        int deviceId = byteBuf.readByte() & 0xFF;
        int backupMsg = byteBuf.readByte() & 0xFF;
        int dataLength = byteBuf.readShort() & 0xFF;
        FrameMajorHeader headMsg = new FrameMajorHeader(msgId, groupId, deviceId, dataLength, backupMsg);
        ByteBuf subBuf = ctx.alloc().buffer(dataLength);
        byteBuf.readBytes(subBuf, dataLength);
        ctx.fireChannelRead(new FrameMajor(headMsg, subBuf));
    }
}
 
Example 2
Project: ClusterDeviceControlPlatform   File: FrameRecognitionInBoundHandler.java   Source Code and License Vote up 6 votes
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
    while (true) {
        if (byteBuf.readableBytes() < FrameSetting.FRAME_HEAD_LENGTH) {
            return;
        }
        if (byteBuf.readByte() != FrameSetting.MAJOR_FRAME_HEAD_1
                || byteBuf.readByte() != FrameSetting.MAJOR_FRAME_HEAD_2) {
            return;
        }
        int groupId = byteBuf.readByte() & 0xFF;
        int msgId = byteBuf.readByte() & 0xFF;
        int deviceId = byteBuf.readByte() & 0xFF;
        int backupMsg = byteBuf.readByte() & 0xFF;
        int dataLength = byteBuf.readShort() & 0xFF;
        FrameMajorHeader headMsg = new FrameMajorHeader(msgId, groupId, deviceId, dataLength, backupMsg);
        ByteBuf subBuf = ctx.alloc().buffer(dataLength);
        byteBuf.readBytes(subBuf, dataLength);
        ctx.fireChannelRead(new FrameMajor(headMsg, subBuf));
    }
}
 
Example 3
Project: ToughExpansion   File: PacketConfigSync.java   Source Code and License Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public void fromBytes(ByteBuf buf) {
	short len = buf.readShort();
	byte[] compressedBody = new byte[len];

	for (short i = 0; i < len; i++) {
		compressedBody[i] = buf.readByte();
	}

	try {
		ObjectInputStream obj = new ObjectInputStream(new GZIPInputStream(new ByteArrayInputStream(compressedBody)));
		values = (Map<String, Object>) obj.readObject();
		obj.close();
	}
	catch (Exception e) {
		Throwables.propagate(e);
	}
}
 
Example 4
Project: cr-private-server   File: PacketDecoder.java   Source Code and License Vote up 6 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	if (!hasHeader) {
		if (in.readableBytes() >= 7) {
			short id = in.readShort();
			int payloadLength = in.readMedium();
			short version = in.readShort();

			hasHeader = true;
			header.id = id;
			header.payload = new byte[payloadLength];
		}
	} else {
		if (in.readableBytes() >= header.payload.length) {
			in.readBytes(header.payload);
			hasHeader = false;

			crypto.decryptPacket(header);

			ClientMessage message = processPacket();
			if (message != null) {
				out.add(message);
			}
		}
	}
}
 
Example 5
Project: LibraSock   File: LibraDecoder.java   Source Code and License Vote up 6 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	try {
		//LibraLog.info("decode is bytebuf in is :" + JsonUtil.ObjectToJsonString(in.array()));
		// 空的buf
		if (in instanceof EmptyByteBuf || in.readableBytes() < 0) {
			return;
		}
		short length = in.readShort();
		if (length != in.readableBytes()) {
			return;
		}
		// 反序列化
		LibraMessage message = LibraMessage.decode(in);
		if (message == null) {
			return;
		}
		out.add(message);
	} catch (Exception e) {
		e.printStackTrace();
		return;
	}
}
 
Example 6
Project: kcp-netty   File: KcpRttClientHandler.java   Source Code and License Vote up 6 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf buf = (ByteBuf) msg;
    int curCount = buf.readShort();

    if (curCount == -1) {
        scheduleSrv.schedule(new Runnable() {
            @Override
            public void run() {
                ctx.close();
            }
        }, 3, TimeUnit.SECONDS);
    } else {
        int idx = curCount - 1;
        long time = buf.readInt();
        if (rtts[idx] != -1) {
            log.error("???");
        }
        //log.info("rcv count {} {}", curCount, System.currentTimeMillis());
        rtts[idx] = (int) (System.currentTimeMillis() - startTime - time);

        log.info("rtt {}: {}", curCount, rtts[idx]);
    }

    buf.release();
}
 
Example 7
Project: EndermanEvolution   File: PacketFriendermanRegistrySync.java   Source Code and License Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public void fromBytes(ByteBuf buf) {
	short len = buf.readShort();
	byte[] compressedBody = new byte[len];

	for (short i = 0; i < len; i++) {
		compressedBody[i] = buf.readByte();
	}

	try {
		ObjectInputStream obj = new ObjectInputStream(new GZIPInputStream(new ByteArrayInputStream(compressedBody)));
		registry = (Map<Integer, UUID>) obj.readObject();
		obj.close();
	}
	catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 8
Project: Quavo   File: MachineInformation.java   Source Code and License Vote up 5 votes
/**
 * Decodes the machine information of the user during the {@link WorldLoginDecoder}.
 * 
 * @param buffer The {@link ByteBuf}.
 * @return The created machine information.
 */
public static MachineInformation decode(ByteBuf buffer) {
	buffer.readByte();
	int osArch = buffer.readByte();
	boolean is64Bit = buffer.readByte() == 1;
	int osBuild = buffer.readByte();
	int vendor = buffer.readByte();
	buffer.readByte();
	buffer.readByte();
	buffer.readByte();
	buffer.readByte();
	buffer.readShort();
	buffer.readByte();
	buffer.readMedium();
	buffer.readShort();
	ByteBufUtils.readJagString(buffer);
	ByteBufUtils.readJagString(buffer);
	ByteBufUtils.readJagString(buffer);
	ByteBufUtils.readJagString(buffer);
	buffer.readByte();
	buffer.readShort();
	ByteBufUtils.readJagString(buffer);
	ByteBufUtils.readJagString(buffer);
	buffer.readByte();
	buffer.readByte();
	return new MachineInformation(osArch, is64Bit, osBuild, vendor);
}
 
Example 9
Project: FlexMC   File: MessageS27EntityRelMoveLook.java   Source Code and License Vote up 5 votes
@Override
public void read( ByteBuf buf ) throws IOException {
    entityId = readVarInt( buf );
    deltaX = buf.readShort();
    deltaY = buf.readShort();
    deltaZ = buf.readShort();
    yaw = buf.readFloat();
    pitch = buf.readFloat();
    onGround = buf.readBoolean();
}
 
Example 10
Project: message-broker   File: AmqpDecoder.java   Source Code and License Vote up 5 votes
private void parseFrame(ByteBuf buffer, List<Object> out) throws Exception {
    buffer.markReaderIndex();
    if (buffer.readableBytes() > FRAME_SIZE_WITHOUT_PAYLOAD) {
        byte type = buffer.readByte();
        int channel = buffer.readShort();
        long payloadSize = buffer.readInt();

        long estimatedRemainingSize = payloadSize + 1;
        if (buffer.readableBytes() < estimatedRemainingSize) {
            buffer.resetReaderIndex();
            return;
        }

        GeneralFrame frame = null;
        switch (type) {
            case 1: // Method
                short amqpClass = buffer.readShort();
                short amqpMethod = buffer.readShort();
                AmqMethodBodyFactory factory = methodRegistry.getFactory(amqpClass, amqpMethod);

                frame = factory.newInstance(buffer, channel, payloadSize);
                break;
            case 2: // Header
                frame = HeaderFrame.parse(buffer, channel);
                break;
            case 3: // Body
                frame = ContentFrame.parse(buffer, channel, payloadSize);
                break;
            case 4: // Heartbeat
                throw new Exception("Method Not implemented");
        }

        byte frameEnd = buffer.readByte();
        if (frameEnd != (byte) GeneralFrame.FRAME_END) {
            throw new Exception("Invalid AMQP frame");
        }

        out.add(frame);
    }
}
 
Example 11
Project: uniquecrops   File: PacketUCEffect.java   Source Code and License Vote up 5 votes
@Override
public void fromBytes(ByteBuf buf) {

	type = EnumParticleTypes.values()[buf.readShort()];
	x = buf.readDouble();
	y = buf.readDouble();
	z = buf.readDouble();
	loopSize = buf.readInt();
}
 
Example 12
Project: CustomWorldGen   File: ForgeMessage.java   Source Code and License Vote up 5 votes
@Override
void fromBytes(ByteBuf bytes)
{
    dimensionId = bytes.readInt();
    byte[] data = new byte[bytes.readShort()];
    bytes.readBytes(data);
    providerId = new String(data, Charsets.UTF_8);
}
 
Example 13
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 14
Project: FlexMC   File: MessageC00HandHake.java   Source Code and License Vote up 5 votes
@Override
public void read( ByteBuf buf ) throws IOException {
    protocolVersion = readVarInt( buf );
    serverAddress = readString( buf );
    port = buf.readShort();
    nextState = readVarInt( buf );
}
 
Example 15
Project: incubator-plc4x   File: IsoTPProtocol.java   Source Code and License Vote up 5 votes
private Tpdu decodeError(ByteBuf userData, List<Parameter> parameters) {
    Tpdu tpdu;
    short destinationReference = userData.readShort();
    RejectCause rejectCause = RejectCause.valueOf(userData.readByte());
    tpdu = new ErrorTpdu(destinationReference, rejectCause, parameters, userData);
    return tpdu;
}
 
Example 16
Project: FlexMC   File: MessageS26EntityRelMove.java   Source Code and License Vote up 5 votes
@Override
public void read( ByteBuf buf ) throws IOException {
    entityId = readVarInt( buf );
    deltaX = buf.readShort();
    deltaY = buf.readShort();
    deltaZ = buf.readShort();
    onGround = buf.readBoolean();
}
 
Example 17
Project: FlexMC   File: MessageC1AHeldItemChange.java   Source Code and License Vote up 4 votes
@Override
public void read( ByteBuf buf ) throws IOException {
    slot = buf.readShort();
}
 
Example 18
Project: drift   File: HeaderMessageEncoding.java   Source Code and License Vote up 4 votes
@Override
@SuppressFBWarnings("DLS_DEAD_LOCAL_STORE")
public Object readResponse(ByteBuf buffer, int sequenceId, MethodMetadata method)
        throws Exception
{
    short magic = buffer.readShort();
    verify(magic == HEADER_MAGIC, "Unexpected response header magic");
    short flags = buffer.readShort();
    verify(flags == 1, "Unexpected response header flags");

    int frameSequenceId = buffer.readInt();
    if (frameSequenceId != sequenceId) {
        throw new TApplicationException(BAD_SEQUENCE_ID, method.getName() + " failed: out of sequence response");
    }
    int headerSize = buffer.readShort() << 2;

    ByteBuf messageHeader = buffer.readBytes(headerSize);
    int protocolId = messageHeader.readUnsignedByte();
    verify(protocolId == this.protocolId, "response protocol is different than request protocol");

    int numberOfTransforms = messageHeader.readUnsignedByte();
    verify(numberOfTransforms < 128, "Too many transforms for response");

    boolean gzipCompressed = false;
    for (int i = 0; i < numberOfTransforms; i++) {
        int transform = messageHeader.readUnsignedByte();
        verify(transform == 0x01, "Unsupported response transform");
        gzipCompressed = true;
    }

    // Currently we ignore response headers from the server because there is no API to fetch the headers
    Map<String, String> normalHeaders = decodeHeaders(NORMAL_HEADERS, messageHeader);
    Map<String, String> persistentHeaders = decodeHeaders(PERSISTENT_HEADERS, messageHeader);

    ByteBuf message = buffer.readBytes(buffer.readableBytes());
    if (gzipCompressed) {
        // todo decompress
        throw new TTransportException("gzip compression not implemented");
    }

    return MessageEncoding.decodeResponse(protocolFactory, message, sequenceId, method);
}
 
Example 19
Project: reactive-pg-client   File: DataType.java   Source Code and License Vote up 4 votes
@Override
public Short decodeBinary(int len, ByteBuf buff) {
  return buff.readShort();
}
 
Example 20
Project: jsf-sdk   File: ProtocolUtil.java   Source Code and License Vote up 4 votes
public static BaseMessage decode(ByteBuf byteBuf){
        MessageHeader header = null;
        Integer msgLength = byteBuf.readableBytes() + 6;//magiccode + msg length(4 byte)
        BaseMessage msg = null;
        ByteBuf deCompress = null;
        try {
            Short headerLength = byteBuf.readShort();
//            int readerIndex = byteBuf.readerIndex();
//            if(readerIndex > byteBuf.readableBytes()){
//                throw new JSFCodecException("codecError:header length error.");
//            }
            //ByteBuf headerBuf = byteBuf.slice(readerIndex,headerLength);
            //byteBuf.skipBytes(headerLength);
            header = CodecUtils.decodeHeader(byteBuf, headerLength);
            header.setHeaderLength(headerLength);
            //是否需要解压
            int compType = header.getCompressType();
            if (compType > 0) {
                if(logger.isTraceEnabled()) {
                    logger.trace("msgId [{}] is deCompressed with processType {}",
                            header.getMsgId(), Constants.CompressType.valueOf((byte) compType));
                }

                byte[] desc = new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(desc);
                byte[] deCom = CompressUtil.deCompress(desc, (byte)compType);
                deCompress = PooledBufHolder.getBuffer(deCom.length);
                deCompress.writeBytes(deCom);
                byteBuf.release();

                header.setLength(deCompress.readableBytes() + 6 + headerLength);
                msg = enclosure(deCompress,header);
            } else {
                header.setLength(msgLength);
                msg = enclosure(byteBuf,header);
            }
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
            RpcException rpcException = ExceptionUtils.handlerException(header, e);
            byteBuf.release();//release the byteBuf when decode hit on error
            if (deCompress != null) deCompress.release();
            throw rpcException;
        }
        return msg;
    }