Example usage for io.netty.buffer ByteBuf readInt

List of usage examples for io.netty.buffer ByteBuf readInt

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readInt.

Prototype

public abstract int readInt();

Source Link

Document

Gets a 32-bit integer at the current readerIndex and increases the readerIndex by 4 in this buffer.

Usage

From source file:com.rs3e.network.session.impl.LoginSession.java

License:Open Source License

private void decodeLobbyLogin(ByteBuf buffer) {
    int secureBufferSize = buffer.readShort() & 0xFFFF;
    if (buffer.readableBytes() < secureBufferSize) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;/*w  ww .j a  va2s  .  co  m*/
    }

    byte[] secureBytes = new byte[secureBufferSize];
    buffer.readBytes(secureBytes);

    ByteBuf secureBuffer = Unpooled.wrappedBuffer(
            new BigInteger(secureBytes).modPow(Constants.JS5PrivateKey, Constants.JS5ModulusKey).toByteArray());
    int blockOpcode = secureBuffer.readUnsignedByte();

    if (blockOpcode != 10) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;
    }

    int[] xteaKey = new int[4];
    for (int key = 0; key < xteaKey.length; key++) {
        xteaKey[key] = secureBuffer.readInt();
    }

    long vHash = secureBuffer.readLong();
    if (vHash != 0L) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;
    }

    String password = ByteBufUtils.readString(secureBuffer);

    long[] loginSeeds = new long[2];
    for (int seed = 0; seed < loginSeeds.length; seed++) {
        loginSeeds[seed] = secureBuffer.readLong();
    }

    byte[] xteaBlock = new byte[buffer.readableBytes()];
    buffer.readBytes(xteaBlock);
    XTEA xtea = new XTEA(xteaKey);
    xtea.decrypt(xteaBlock, 0, xteaBlock.length);

    InputStream xteaBuffer = new InputStream(xteaBlock);

    boolean decodeAsString = xteaBuffer.readByte() == 1;
    String username = decodeAsString ? xteaBuffer.readString()
            : Base37Utils.decodeBase37(xteaBuffer.readLong());

    @SuppressWarnings("unused")
    int gameType = xteaBuffer.readUnsignedByte();
    @SuppressWarnings("unused")
    int languageID = xteaBuffer.readUnsignedByte();

    @SuppressWarnings("unused")
    int displayMode = xteaBuffer.readByte();
    @SuppressWarnings("unused")
    int screenWidth = xteaBuffer.readUnsignedShort();//Client screen width
    @SuppressWarnings("unused")
    int screenHeight = xteaBuffer.readUnsignedShort();//Client screen height
    @SuppressWarnings("unused")
    int anUnknownByte = xteaBuffer.readByte();

    byte[] randomData = new byte[24];
    for (int i = 0; i < randomData.length; i++) {
        randomData[i] = (byte) (xteaBuffer.readByte() & 0xFF);
    }

    @SuppressWarnings("unused")
    String clientSettings = xteaBuffer.readString();

    int indexFiles = xteaBuffer.readByte() & 0xff;

    int[] crcValues = new int[indexFiles];

    for (int i = 0; i < crcValues.length; i++) {
        crcValues[i] = xteaBuffer.readInt();
    }

    int length = xteaBuffer.readUnsignedByte();

    byte[] machineData = new byte[length];
    for (int data = 0; data < machineData.length; data++) {
        machineData[data] = (byte) xteaBuffer.readUnsignedByte();
    }

    xteaBuffer.readInt();//Packet receive count
    xteaBuffer.readString();//Some param string (empty)
    xteaBuffer.readInt();//Another param (0) 
    xteaBuffer.readInt();//Yet another param (2036537831)

    String serverToken = xteaBuffer.readString();
    if (!serverToken.equals(Constants.SERVER_TOKEN)) {
        channel.write(new LoginResponse(LoginResponse.BAD_SESSION));
        return;
    }

    xteaBuffer.readByte();//Final param (2424)

    if (GeneralUtils.invalidAccountName(username)) {
        //session.getLoginPackets().sendClientPacket(3);//Invalid username or password
        channel.write(new LoginResponse(LoginResponse.INVALID_UN_PWD));
        return;
    }
    /*
    if (World.getPlayers().size() >= Settings.PLAYERS_LIMIT - 10) {
       session.getLoginPackets().sendClientPacket(7);//World full
       return;
    }
    if (World.containsPlayer(username) || World.containsLobbyPlayer(username)) {
       session.getLoginPackets().sendClientPacket(5);//Account not logged out
       return;
    }
    if (AntiFlood.getSessionsIP(session.getIP()) > 3) {
       session.getLoginPackets().sendClientPacket(9);//Login limit exceeded
       return;
    }*/
    Player player;// = new Player(new PlayerDefinition(username, password));
    if (!SerializableFilesManager.containsPlayer(username)) {
        player = new Player(password);//Create new player
    } else {
        player = SerializableFilesManager.loadPlayer(username);
        if (player == null) {
            //session.getLoginPackets().sendClientPacket(20);//Invalid login server
            channel.write(new LoginResponse(LoginResponse.INVALID_LOGIN_SERVER));
            return;
        }
        /*if (!SerializableFilesManager.createBackup(username)) {
           //session.getLoginPackets().sendClientPacket(20);//Invalid login server
           //return;
        }*/
        if (!player.isCorrectPassword(password)) {
            //session.getLoginPackets().sendClientPacket(3);
            channel.write(new LoginResponse(LoginResponse.INVALID_UN_PWD));
            return;
        }
    } // || player.getBanned() > Utils.currentTimeMillis()
    if (player.isPermBanned()) {
        //session.getLoginPackets().sendClientPacket(4);//Account disabled
        channel.write(new LoginResponse(LoginResponse.ACCOUNT_DISABLED));
        return;
    } //24 = account does not exist
    player.lobbyInit(context.channel(), username);

    /*int returnCode = 2;
    if (FileManager.contains(username)) {
       player = (Player) FileManager.load(username);
       if (player == null) {
    returnCode = 24;
       } else if (!password.equals(player.getDefinition().getPassword()) && !Constants.isOwnerIP(channel.getRemoteAddress().toString().split(":")[0].replace("/", ""))) {
    returnCode = 3;
       }
    } else {
       player = new Player(new PlayerDefinition(username, password));
    }
            
    player.init(channel, currentLoginType);
    World.getWorld().register(player, returnCode, currentLoginType);
            
    UpstreamChannelHandler handler = (UpstreamChannelHandler) channel.getPipeline().get("upHandler");
    handler.setPlayer(player);
            
    context.getChannel().setAttachment(player);
            
    channel.getPipeline().replace("decoder", "decoder", new InBufferDecoder());*/
}

From source file:com.savageboy74.savagetech.network.message.MessageTileEntityBase.java

License:Open Source License

@Override
public void fromBytes(ByteBuf buf) {
    this.x = buf.readInt();
    this.y = buf.readInt();
    this.z = buf.readInt();
    this.orientation = buf.readByte();
    this.state = buf.readByte();
    int customNameLength = buf.readInt();
    this.customName = new String(buf.readBytes(customNameLength).array());
    int ownerLength = buf.readInt();
    this.owner = new String(buf.readBytes(ownerLength).array());
}

From source file:com.seagate.kinetic.common.protocol.codec.KineticDecoder.java

License:Open Source License

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

    in.markReaderIndex();//from w ww .j  a v  a  2s .co  m

    // Wait until the length prefix is available
    // (magic ('F') + proto-msg-size + value-size)
    if (in.readableBytes() < 9) {
        in.resetReaderIndex();
        return;
    }

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

    // 2. protobuf message size
    int protoMessageLength = in.readInt();

    // 3. attched value size
    int attachedValueLength = in.readInt();

    // wait until whole message is available
    if (in.readableBytes() < (protoMessageLength + attachedValueLength)) {
        in.resetReaderIndex();
        return;
    }

    // 4. read protobuf message
    byte[] decoded = new byte[protoMessageLength];
    in.readBytes(decoded);

    // kinetic message
    KineticMessage km = new KineticMessage();

    // construct protobuf message
    Message.Builder mbuilder = Message.newBuilder();

    try {
        mbuilder.mergeFrom(decoded);
    } catch (Exception e) {
        in.resetReaderIndex();

        logger.log(Level.WARNING, e.getMessage(), e);

        throw new RuntimeException(e);
    }

    // 5. read attched value if any
    if (attachedValueLength > 0) {
        // construct byte[]
        byte[] attachedValue = new byte[attachedValueLength];
        // read from buffer
        in.readBytes(attachedValue);
        // set to message
        // mbuilder.setValue(ByteString.copyFrom(attachedValue));
        km.setValue(attachedValue);
    }

    Message message = mbuilder.build();

    km.setMessage(message);

    // get command bytes
    ByteString commandBytes = message.getCommandBytes();

    // build command
    Command.Builder commandBuilder = Command.newBuilder();

    try {
        commandBuilder.mergeFrom(commandBytes);
        km.setCommand(commandBuilder.build());
    } catch (InvalidProtocolBufferException e) {
        logger.log(Level.WARNING, e.getMessage(), e);
    }

    // the whole message
    out.add(km);

    // print inbound message
    if (printMessage) {

        logger.info("Inbound protocol message: ");

        String printMsg = ProtocolMessageUtil.toString(km);

        logger.info(printMsg);
    }
}

From source file:com.seventh_root.ld33.client.network.LD33ClientBoundPacketDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    byte[] output = new byte[in.readableBytes()];
    in.readBytes(output);//w  ww .j  a  v  a  2 s  .  c  o  m
    System.out.println(Arrays.toString(output));
    in.resetReaderIndex();
    while (in.isReadable()) {
        int id = in.readInt();
        switch (id) {
        case 0:
            byte[] encodedPublicKey = new byte[in.readInt()];
            in.readBytes(encodedPublicKey);
            out.add(new PublicKeyClientBoundPacket(encodedPublicKey));
            break;
        case 1:
            out.add(new PlayerLoginClientBoundPacket());
            break;
        case 2:
            String joiningPlayerUUID = readString(in);
            String joiningPlayerName = readString(in);
            int joiningPlayerResources = in.readInt();
            out.add(new PlayerJoinClientBoundPacket(UUID.fromString(joiningPlayerUUID), joiningPlayerName,
                    joiningPlayerResources));
            break;
        case 3:
            String quittingPlayerUUID = readString(in);
            String quittingPlayerName = readString(in);
            out.add(new PlayerQuitClientBoundPacket(UUID.fromString(quittingPlayerUUID), quittingPlayerName));
            break;
        case 4:
            String loginResponseMessage = readString(in);
            boolean loginSuccess = in.readBoolean();
            out.add(new PlayerLoginResponseClientBoundPacket(loginResponseMessage, loginSuccess));
            break;
        case 5:
            String spawningUnitUUID = readString(in);
            String spawningUnitPlayerUUID = readString(in);
            int spawningUnitX = in.readInt();
            int spawningUnitY = in.readInt();
            String type = readString(in);
            long spawningUnitCompletionTime = in.readLong();
            Unit unit;
            switch (type) {
            case "wall":
                unit = new Wall(UUID.fromString(spawningUnitUUID),
                        Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)),
                        client.getWorldPanel().getWorld().getTileAt(spawningUnitX, spawningUnitY),
                        spawningUnitCompletionTime);
                break;
            case "dragon":
                unit = new Dragon(UUID.fromString(spawningUnitUUID),
                        Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)),
                        client.getWorldPanel().getWorld().getTileAt(spawningUnitX, spawningUnitY),
                        spawningUnitCompletionTime);
                break;
            case "flag":
                unit = new Flag(UUID.fromString(spawningUnitUUID),
                        Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)),
                        client.getWorldPanel().getWorld().getTileAt(spawningUnitX, spawningUnitY),
                        spawningUnitCompletionTime);
                break;
            default:
                unit = null;
                break;
            }
            out.add(new UnitSpawnClientBoundPacket(unit));
            break;
        case 6:
            String movingUnitUUID = readString(in);
            int movingUnitX = in.readInt();
            int movingUnitY = in.readInt();
            int movingUnitTargetX = in.readInt();
            int movingUnitTargetY = in.readInt();
            out.add(new UnitMoveClientBoundPacket(
                    Unit.getByUUID(null, client.getWorldPanel().getWorld(), UUID.fromString(movingUnitUUID)),
                    movingUnitX, movingUnitY, movingUnitTargetX, movingUnitTargetY));
            break;
        case 7:
            String chatMessage = readString(in);
            out.add(new ChatMessageClientBoundPacket(chatMessage));
            break;
        case 8:
            String purchasingPlayerUUID = readString(in);
            int purchasedUnitX = in.readInt();
            int purchasedUnitY = in.readInt();
            String purchasedUnitType = readString(in);
            out.add(new UnitPurchaseClientBoundPacket(UUID.fromString(purchasingPlayerUUID), purchasedUnitX,
                    purchasedUnitY, purchasedUnitType));
            break;
        }
    }
}

From source file:com.seventh_root.ld33.server.network.LD33ServerBoundPacketDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    while (in.isReadable()) {
        int id = in.readInt();
        switch (id) {
        case 0://  w w w .ja v a  2s .  c  o  m
            byte[] encodedPublicKey = new byte[in.readInt()];
            in.readBytes(encodedPublicKey);
            out.add(new PublicKeyServerBoundPacket(encodedPublicKey));
            break;
        case 1:
            String loggingInPlayerName = readString(in);
            byte[] encryptedPassword = new byte[in.readInt()];
            in.readBytes(encryptedPassword);
            boolean signUp = in.readBoolean();
            out.add(new PlayerLoginServerBoundPacket(loggingInPlayerName, encryptedPassword, signUp));
            break;
        case 2:
            out.add(new PlayerJoinServerBoundPacket());
            break;
        case 3:
            out.add(new PlayerQuitServerBoundPacket());
            break;
        case 4:
            String loginResponseMessage = readString(in);
            boolean loginSuccess = in.readBoolean();
            out.add(new PlayerLoginResponseServerBoundPacket(loginResponseMessage, loginSuccess));
            break;
        case 5:
            String spawningUnitUUID = readString(in);
            String spawningUnitPlayerUUID = readString(in);
            int spawningUnitX = in.readInt();
            int spawningUnitY = in.readInt();
            String spawningUnitType = readString(in);
            long spawningUnitCompletionTime = in.readLong();
            Unit spawningUnit;
            switch (spawningUnitType) {
            case "wall":
                spawningUnit = new Wall(UUID.fromString(spawningUnitUUID),
                        Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)),
                        server.getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime);
                break;
            case "dragon":
                spawningUnit = new Dragon(UUID.fromString(spawningUnitUUID),
                        Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)),
                        server.getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime);
                break;
            case "flag":
                spawningUnit = new Flag(UUID.fromString(spawningUnitUUID),
                        Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)),
                        server.getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime);
                break;
            default:
                spawningUnit = null;
                break;
            }
            out.add(new UnitSpawnServerBoundPacket(spawningUnit));
            break;
        case 6:
            String movingUnitUUID = readString(in);
            int movingUnitTargetX = in.readInt();
            int movingUnitTargetY = in.readInt();
            out.add(new UnitMoveServerBoundPacket(Unit.getByUUID(server.getDatabaseConnection(),
                    server.getWorld(), UUID.fromString(movingUnitUUID)), movingUnitTargetX, movingUnitTargetY));
            break;
        case 7:
            String chatMessage = readString(in);
            out.add(new ChatMessageServerBoundPacket(chatMessage));
            break;
        case 8:
            int purchasedUnitX = in.readInt();
            int purchasedUnitY = in.readInt();
            String purchasedUnitType = readString(in);
            out.add(new UnitPurchaseServerBoundPacket(purchasedUnitX, purchasedUnitY, purchasedUnitType));
            break;
        }
    }
}

From source file:com.smithsmodding.smithscore.common.player.event.PlayersConnectedUpdatedEvent.java

/**
 * Function used by the instance created on the receiving side to reset its state from the sending side stored
 * by it in the Buffer before it is being fired on the NetworkRelayBus.
 *
 * @param pMessageBuffer The ByteBuffer from the IMessage used to Synchronize the implementing events.
 *//*w w  w.j a va  2 s  .c o m*/
@Override
public void readFromMessageBuffer(ByteBuf pMessageBuffer) {
    int pairCount = pMessageBuffer.readInt();

    for (int pairIndex = 0; pairIndex < pairCount; pairIndex++) {
        commonSidedJoinedMap.put(NetworkHelper.readUUID(pMessageBuffer),
                ByteBufUtils.readUTF8String(pMessageBuffer));
    }
}

From source file:com.smithsmodding.smithscore.common.player.event.PlayersOnlineUpdatedEvent.java

/**
 * Function used by the instance created on the receiving side to reset its state from the sending side stored
 * by it in the Buffer before it is being fired on the NetworkRelayBus.
 *
 * @param pMessageBuffer The ByteBuffer from the IMessage used to Synchronize the implementing events.
 *//*from w ww.  j  a va  2s  . com*/
@Override
public void readFromMessageBuffer(ByteBuf pMessageBuffer) {
    int pairCount = pMessageBuffer.readInt();

    for (int pairIndex = 0; pairIndex < pairCount; pairIndex++) {
        commonSidedOnlineMap.add(NetworkHelper.readUUID(pMessageBuffer));
    }
}

From source file:com.smithsmodding.smithscore.util.common.positioning.Coordinate2D.java

public static Coordinate2D fromBytes(ByteBuf pData) {
    return new Coordinate2D(pData.readInt(), pData.readInt());
}

From source file:com.smithsmodding.smithscore.util.common.positioning.Coordinate3D.java

public static Coordinate3D fromBytes(ByteBuf pData) {
    return new Coordinate3D(pData.readInt(), pData.readInt(), pData.readInt());
}

From source file:com.smithsmodding.tinystorage.network.message.MessageSyncPlayerData.java

@Override
public void fromBytes(ByteBuf buf) {
    playerList = new HashMap<UUID, String>();
    int IDCount = buf.readInt();
    for (int IDNumber = 0; IDNumber < IDCount; IDNumber++) {
        UUID ID = UUID.fromString(ByteBufUtils.readUTF8String(buf));
        String Name = ByteBufUtils.readUTF8String(buf);
        playerList.put(ID, Name);
    }/* www.j  av  a2 s  .  c  om*/
    playerGlobalFriends = new HashMap<UUID, String>();
    int IDCountGlobal = buf.readInt();
    for (int IDNumber = 0; IDNumber < IDCountGlobal; IDNumber++) {
        UUID ID = UUID.fromString(ByteBufUtils.readUTF8String(buf));
        String Name = ByteBufUtils.readUTF8String(buf);
        playerGlobalFriends.put(ID, Name);
    }
    playerUUIDs = new ArrayList<String>();
    int count = buf.readInt();
    for (int i = 0; i < count; i++) {
        String uuid = ByteBufUtils.readUTF8String(buf);
        playerUUIDs.add(uuid);
    }
}