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

The following examples show how to use io.netty.buffer.ByteBuf#getShort() . 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 check out the related API usage on the sidebar.
Example 1
Source File: ServerPacketDecoder.java    From MirServer-Netty with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

	int    pidPos     = 4;
	short  protocolId = in.getShort(pidPos);

	Protocol protocol = Protocol.getServerProtocol(protocolId);

	Class<? extends ServerPacket> packetClass;
	if (null == protocol) {
		LogManager.getLogger().error("unknow protocol id {}",protocolId);
		packetClass = ServerPacket.class;
	} else {
		try {
			packetClass = (Class<? extends ServerPacket>) Class.forName(ServerPacket.class.getCanonicalName() + "$" + protocol.name);
		} catch (ClassNotFoundException e) {
			packetClass = ServerPacket.class;
		}
	}
	ServerPacket packet = packetClass.newInstance();
	packet.readPacket(in);
	packet.protocol = protocol;

	out.add(packet);
}
 
Example 2
Source File: JT808Decoder.java    From jt808-netty with MIT License 6 votes vote down vote up
public DataPacket parse(ByteBuf bb) {
    DataPacket packet = null;
    short msgId = bb.getShort(bb.readerIndex());
    switch (msgId) {
        case TERNIMAL_MSG_HEARTBEAT:
            packet = new HeartBeatMsg(bb);
            break;
        case TERNIMAL_MSG_LOCATION:
            packet = new LocationMsg(bb);
            break;
        case TERNIMAL_MSG_REGISTER:
            packet = new RegisterMsg(bb);
            break;
        case TERNIMAL_MSG_AUTH:
            packet = new AuthMsg(bb);
            break;
        case TERNIMAL_MSG_LOGOUT:
            packet = new LogOutMsg(bb);
            break;
        default:
            packet = new DataPacket(bb);
            break;
    }
    packet.parse();
    return packet;
}
 
Example 3
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
public static String getMethod(ByteBuf byteBuf) {
  int offset = Short.BYTES;

  int serviceLength = byteBuf.getShort(offset);
  offset += Short.BYTES + serviceLength;

  int methodLength = byteBuf.getShort(offset);
  offset += Short.BYTES;

  return byteBuf.toString(offset, methodLength, StandardCharsets.UTF_8);
}
 
Example 4
Source File: KcpRttServerHandler.java    From kcp-netty with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf buf = (ByteBuf) msg;
    short curCount = buf.getShort(buf.readerIndex());
    ctx.writeAndFlush(msg);

    if (curCount == -1) {
        ctx.close();
    }
}
 
Example 5
Source File: TcpRttServerHandler.java    From kcp-netty with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf buf = (ByteBuf) msg;
    short curCount = buf.getShort(buf.readerIndex());
    ctx.writeAndFlush(msg);

    if (curCount == -1) {
        ctx.close();
    }
}
 
Example 6
Source File: TcpRttDecoder.java    From kcp-netty with MIT License 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 8) {
        return;
    }

    short dataLen = in.getShort(in.readerIndex() + 6);
    if (in.readableBytes() < dataLen) {
        return;
    }

    ByteBuf msg = in.readRetainedSlice(8 + dataLen);
    out.add(msg);
}
 
Example 7
Source File: VotifierProtocolDifferentiator.java    From NuVotifier with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception {
    // Determine the number of bytes that are available.
    int readable = buf.readableBytes();

    if (readable < 2) {
        // Some retarded voting sites (PMC?) seem to send empty buffers for no good reason.
        return;
    }

    short readMagic = buf.getShort(0);
    VotifierSession session = ctx.channel().attr(VotifierSession.KEY).get();

    if (readMagic == PROTOCOL_2_MAGIC) {
        // Short 0x733A + Message = Protocol v2 Vote
        session.setVersion(VotifierSession.ProtocolVersion.TWO);

        if (!testMode) {
            ctx.pipeline().addAfter("protocolDifferentiator", "protocol2LengthDecoder", new LengthFieldBasedFrameDecoder(1024, 2, 2, 0, 4));
            ctx.pipeline().addAfter("protocol2LengthDecoder", "protocol2StringDecoder", new StringDecoder(StandardCharsets.UTF_8));
            ctx.pipeline().addAfter("protocol2StringDecoder", "protocol2VoteDecoder", new VotifierProtocol2Decoder());
            ctx.pipeline().addAfter("protocol2VoteDecoder", "protocol2StringEncoder", new StringEncoder(StandardCharsets.UTF_8));
            ctx.pipeline().remove(this);
        }
    } else {
        if (!allowv1) {
            throw V2_ONLY;
        }
        // Probably Protocol v1 Vote Message
        session.setVersion(VotifierSession.ProtocolVersion.ONE);
        if (!testMode) {
            ctx.pipeline().addAfter("protocolDifferentiator", "protocol1Handler", new VotifierProtocol1Decoder());
            ctx.pipeline().remove(this);
        }
    }
}
 
Example 8
Source File: KcpRttExampleServer.java    From java-Kcp with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReceive(ByteBuf buf, Ukcp kcp,int protocolType) {
    short curCount = buf.getShort(buf.readerIndex());
    System.out.println(Thread.currentThread().getName()+"  收到消息 "+curCount);
    kcp.writeOrderedReliableMessage(buf);
    if (curCount == -1) {
        kcp.notifyCloseEvent();
    }
}
 
Example 9
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
public static ByteBuf getMetadata(ByteBuf byteBuf) {
  int offset = Short.BYTES;

  int serviceLength = byteBuf.getShort(offset);
  offset += Short.BYTES + serviceLength;

  int methodLength = byteBuf.getShort(offset);
  offset += Short.BYTES + methodLength;

  int tracingLength = byteBuf.getShort(offset);
  offset += Short.BYTES + tracingLength;

  int metadataLength = byteBuf.readableBytes() - offset;
  return metadataLength > 0 ? byteBuf.slice(offset, metadataLength) : Unpooled.EMPTY_BUFFER;
}
 
Example 10
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
public static ByteBuf getTracing(ByteBuf byteBuf) {
  int offset = Short.BYTES;

  int serviceLength = byteBuf.getShort(offset);
  offset += Short.BYTES + serviceLength;

  int methodLength = byteBuf.getShort(offset);
  offset += Short.BYTES + methodLength;

  int tracingLength = byteBuf.getShort(offset);
  offset += Short.BYTES;

  return tracingLength > 0 ? byteBuf.slice(offset, tracingLength) : Unpooled.EMPTY_BUFFER;
}
 
Example 11
Source File: DefaultLispEncapsulatedControl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public LispEncapsulatedControl readFrom(ByteBuf byteBuf) throws
        LispParseError, LispReaderException, DeserializationException {

    if (byteBuf.readerIndex() != 0) {
        return null;
    }

    boolean securityFlag = ByteOperator.getBit(byteBuf.readByte(),
                                                    SECURITY_INDEX);
    // let's skip the reserved field
    byteBuf.skipBytes(RESERVED_SKIP_LENGTH);

    short totalLength = byteBuf.getShort(byteBuf.readerIndex() + 2);

    byte[] ipHeaderByte = new byte[totalLength];
    byteBuf.getBytes(byteBuf.readerIndex(), ipHeaderByte, 0, totalLength);

    IP innerIpHeader = IP.deserializer().deserialize(ipHeaderByte, 0,
                                                     totalLength);

    UDP innerUdp = (UDP) innerIpHeader.getPayload();
    Data data = (Data) innerUdp.getPayload();
    ByteBuf msgBuffer = Unpooled.buffer();
    msgBuffer.writeBytes(data.getData());

    LispMessageReader reader = LispMessageReaderFactory.getReader(msgBuffer);
    LispMessage innerMessage = (LispMessage) reader.readFrom(msgBuffer);

    return new DefaultLispEncapsulatedControl(securityFlag, innerIpHeader,
                                              innerUdp, innerMessage);
}
 
Example 12
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
public static ByteBuf getMetadata(ByteBuf byteBuf) {
  int offset = Short.BYTES;

  int serviceLength = byteBuf.getShort(offset);
  offset += Short.BYTES + serviceLength;

  int methodLength = byteBuf.getShort(offset);
  offset += Short.BYTES + methodLength;

  int tracingLength = byteBuf.getShort(offset);
  offset += Short.BYTES + tracingLength;

  int metadataLength = byteBuf.readableBytes() - offset;
  return metadataLength > 0 ? byteBuf.slice(offset, metadataLength) : Unpooled.EMPTY_BUFFER;
}
 
Example 13
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
public static ByteBuf getTracing(ByteBuf byteBuf) {
  int offset = Short.BYTES;

  int serviceLength = byteBuf.getShort(offset);
  offset += Short.BYTES + serviceLength;

  int methodLength = byteBuf.getShort(offset);
  offset += Short.BYTES + methodLength;

  int tracingLength = byteBuf.getShort(offset);
  offset += Short.BYTES;

  return tracingLength > 0 ? byteBuf.slice(offset, tracingLength) : Unpooled.EMPTY_BUFFER;
}
 
Example 14
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
public static String getMethod(ByteBuf byteBuf) {
  int offset = Short.BYTES;

  int serviceLength = byteBuf.getShort(offset);
  offset += Short.BYTES + serviceLength;

  int methodLength = byteBuf.getShort(offset);
  offset += Short.BYTES;

  return byteBuf.toString(offset, methodLength, StandardCharsets.UTF_8);
}
 
Example 15
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
public static String getService(ByteBuf byteBuf) {
  int offset = Short.BYTES;

  int serviceLength = byteBuf.getShort(offset);
  offset += Short.BYTES;

  return byteBuf.toString(offset, serviceLength, StandardCharsets.UTF_8);
}
 
Example 16
Source File: ClientPacketDecoder.java    From MirServer-Netty with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

	in = in.order(ByteOrder.LITTLE_ENDIAN);

	short  protocolId;

	if('*' == in.getByte(1) && '*' == in.getByte(2)){
		//connect to gameserver packet, format : cmdIndex**loginId/characterName/clientVersion/cert
		protocolId = Protocol.CM_GAMELOGIN.id;
	}else{
		//normal index packet
		int pidPos = 1 + 4;
		protocolId = in.getShort(pidPos);
	}

	Protocol protocol = Protocol.getClientProtocol(protocolId);

	Class<? extends ClientPacket> packetClass;
	if (null == protocol) {
		LogManager.getLogger().error("unknow protocol id {}",protocolId);
		return ;
	} else {
		try {
			packetClass = (Class<? extends ClientPacket>) Class.forName(packetPackageName + "$" + protocol.name);
		} catch (ClassNotFoundException e) {
			packetClass = ClientPacket.class;
		}
	}
	ClientPacket packet = packetClass.newInstance();
	packet.readPacket(in);
	packet.protocol = protocol;


	out.add(packet);
}
 
Example 17
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
public static int getVersion(ByteBuf byteBuf) {
  return byteBuf.getShort(0) & 0x7FFF;
}
 
Example 18
Source File: ReadTagFragmentedService.java    From ethernet-ip with Apache License 2.0 4 votes vote down vote up
@Override
public ByteBuf decodeResponse(ByteBuf buffer) throws CipResponseException, PartialResponseException {
    MessageRouterResponse response = MessageRouterResponse.decode(buffer);

    int status = response.getGeneralStatus();
    ByteBuf data = response.getData();

    try {
        if (status == 0x00 || status == 0x06) {
            if (status == 0x06 && data.readableBytes() == 0) {
                throw PartialResponseException.INSTANCE;
            }

            boolean structured = data.getShort(data.readerIndex()) == 0x02A0;
            ByteBuf header = structured ? data.readSlice(4) : data.readSlice(2);
            ByteBuf fragment = data.slice().retain();

            buffers.add(fragment);
            offset += fragment.readableBytes();

            if (status == 0x00) {
                synchronized (buffers) {
                    ByteBuf composite = Unpooled.compositeBuffer()
                        .addComponent(header.retain())
                        .addComponents(buffers)
                        .writerIndex(header.readableBytes() + offset)
                        .order(ByteOrder.LITTLE_ENDIAN);

                    // Clean up so this service can be re-used...
                    buffers.clear();
                    offset = 0;

                    return composite;
                }
            } else {
                throw PartialResponseException.INSTANCE;
            }
        } else {
            throw new CipResponseException(status, response.getAdditionalStatus());
        }
    } finally {
        ReferenceCountUtil.release(data);
    }
}
 
Example 19
Source File: Metadata.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
public static int getVersion(ByteBuf byteBuf) {
  return byteBuf.getShort(0) & 0x7FFF;
}
 
Example 20
Source File: Commands.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public static boolean hasChecksum(ByteBuf buffer) {
    return buffer.getShort(buffer.readerIndex()) == magicCrc32c;
}