Jump to content

How do I send data of Objects that are unserializable through packets from the client to the server? [1.16.4]


Junferno

Recommended Posts

My idea here is being able to spawn a MobEntity in the World that the player is in when a certain client-side Event is triggered. Specifically, I need to be able to encode the MobEntity Object (or at least the EntityType Object with the position coordinates) as well as the AbstractSpawner and SpawnReason Objects through a packet to be spawned server-side (I might also need to pass in a World object since I'm not sure if MobEntity.getEntityWorld() would work server-side). As of now, I am only able to send primitive data-types or serializable non-vanilla Objects. I know that encoding non-serializable Objects such as Entity and World is not secure (and it gets an error if I try it anyway), but I'm not sure what else I could do. Thanks in advance!

 

PacketSpawnFearMod.java (running this would get a java.io.NotSerializableException when I attempt to convert the MobEntity, AbstractSpawner, and SpawnReason fields of the PacketSpawnFearMod Object to byte arrays)

package com.junferno.fearmod.packets;

import com.junferno.fearmod.FearMod;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.SpawnReason;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.spawner.AbstractSpawner;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingSpawnEvent;
import net.minecraftforge.fml.network.NetworkEvent;

import java.io.*;
import java.util.function.Supplier;

public class PacketSpawnFearMod implements Serializable {

    private MobEntity entity;
    private AbstractSpawner spawner;
    private SpawnReason spawnReason;

    public PacketSpawnFearMod(MobEntity entity, AbstractSpawner spawner, SpawnReason spawnReason) {
        this.entity = entity;
        this.spawner = spawner;
        this.spawnReason = spawnReason;
    }

    public static byte[] objToByte(PacketSpawnFearMod packet) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        ObjectOutputStream objStream = new ObjectOutputStream(byteStream);
        objStream.writeObject(packet);

        return byteStream.toByteArray();
    }

    public static Object byteToObj(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objStream = new ObjectInputStream(byteStream);

        return objStream.readObject();
    }

    public PacketSpawnFearMod(PacketBuffer buf) {
        try {
            PacketSpawnFearMod packet = (PacketSpawnFearMod) byteToObj(buf.readByteArray());
            this.entity = packet.entity;
            this.spawner = packet.spawner;
            this.spawnReason = packet.spawnReason;
        }
        catch (IOException | ClassNotFoundException e) {
            FearMod.LOGGER.error("Failed to read packet");
            FearMod.LOGGER.error(e.toString());
        }
    }

    public static void encode(PacketSpawnFearMod packet, PacketBuffer buf) {
        try {
            buf.writeByteArray(objToByte(packet));
        }
        catch (IOException e) {
            FearMod.LOGGER.error("Failed to encode packet"); // java.io.NotSerializableException
            FearMod.LOGGER.error(e.toString());
        }
    }

    public static void handle(final PacketSpawnFearMod packet, Supplier<NetworkEvent.Context> context) {
        NetworkEvent.Context ctx = context.get();
        ctx.enqueueWork(() -> {

            MinecraftForge.EVENT_BUS.post(new LivingSpawnEvent.SpecialSpawn(
                    packet.entity,
                    packet.entity.getEntityWorld(),
                    packet.entity.getPosX(),
                    packet.entity.getPosY(),
                    packet.entity.getPosZ(),
                    packet.spawner,
                    packet.spawnReason
            ));

        });

        ctx.setPacketHandled(true);
    }
}

 

I am using Forge 1.16.4 with Java 1.8.0, Gradle 4.10.3, and IntelliJ IDEA Community Edition 2020 on Windows 10

Edited by Junferno
Link to comment
Share on other sites

6 hours ago, diesieben07 said:
  1. Do not at all ever use Java serialization. It is absolutely terrible. It is slow, unsafe and most importantly slooooow.
  2. An EntityType is a registry entry. You can use PacketBuffer#writeRegistryIdUnsafe and readRegistryIdUnsafe to send them.
  3. SpawnReason is an enum, you can use writeEnumValue and readEnumValue.
  4. An AbstractSpawner is attached to a tile entity or entity. For a tile entity you can send the position (BlockPos) for an entity you can send it's entityID.

However, all that said. You should not be doing any of this. The client must not decide when to spawn something. This will enable your mod to be used for malicious clients, as the client can simply tell the server what to spawn - the server will happily do it. Any game logic like this must be done on the server. Why are you doing it on the client?

Thanks for responding! The goal here is to be able to spawn a custom mob instead whenever a specific vanilla mob is spawned. When the LivingSpawnEvent.SpecialSpawn event is called, the spawning of that mob is cancelled and the custom mob is spawned instead. Just through trial and error, I found that the event can only be subscribed to on the client-side.

 

In the bigger picture, I want to be able to have the attributes of MonsterEntitys to be controlled by some external program that changes the values of the mob every few seconds, which is why I am just spawning a subclass of the Entity that contains methods allowing me to change their values. I feel as if this may be a bit unsafe, but I wasn't sure how else to approach this.

 

Here's an example: ModClientEvents#onEntitySpawn

@SubscribeEvent
  public static void onEntitySpawn(LivingSpawnEvent.SpecialSpawn event)
  {
      if(!(event.getEntity() instanceof CreeperEntity) || event.getEntity() instanceof FearCreeperEntity || !event.isCancelable())
          return;

      CreeperEntity creeper = (CreeperEntity) event.getEntity();

      FearCreeperEntity fcreeper = FearCreeperEntity.createFromCreeper(creeper);
      PacketSpawnFearMod packet = new PacketSpawnFearMod(fcreeper, event.getSpawner(), event.getSpawnReason());
      packetRegister.sendToServer(packet);
      FearMod.LOGGER.info("Packet sent");

      event.setCanceled(true);
  }

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I have a problem, I am trying to put two different effects to two different armors but when I run it only the emerald armor effect works. This is the code public class ModArmorItem extends ArmorItem{ private static final Map<ArmorMaterial, MobEffectInstance> MATERIAL_TO_EFFECT_MAP = (new ImmutableMap.Builder<ArmorMaterial, MobEffectInstance>()) .put(ModArmorMaterials.EMERALD, new MobEffectInstance(MobEffects.HERO_OF_THE_VILLAGE,200, 1,false,false, true)) .put(ModArmorMaterials.OBSIDIAN, new MobEffectInstance(MobEffects.FIRE_RESISTANCE,200, 1,false,false, true)).build(); public ModArmorItem(ArmorMaterial pMaterial, Type pType, Properties pProperties) { super(pMaterial, pType, pProperties); } @Override public void onArmorTick(ItemStack stack, Level world, Player player){ if (!world.isClientSide()) { if (hasFullSuitOfArmorOn(player)) { evaluateArmorEffects(player); } } } private void evaluateArmorEffects(Player player) { for (Map.Entry<ArmorMaterial,MobEffectInstance> entry : MATERIAL_TO_EFFECT_MAP.entrySet()){ ArmorMaterial mapArmorMaterial = entry.getKey(); MobEffectInstance mapStatusEffect = entry.getValue(); if (hasCorrectArmorOn(mapArmorMaterial, player)) { addStatusEffectForMaterial(player, mapArmorMaterial, mapStatusEffect); } } } private void addStatusEffectForMaterial(Player player, ArmorMaterial mapArmorMaterial, MobEffectInstance mapStatusEffect) { boolean hasPlayerEffect = player.hasEffect(mapStatusEffect.getEffect()); if (hasCorrectArmorOn(mapArmorMaterial, player) && !hasPlayerEffect) { player.addEffect(new MobEffectInstance(mapStatusEffect)); } } private boolean hasCorrectArmorOn(ArmorMaterial material, Player player) { for (ItemStack armorStack : player.getInventory().armor){ if (!(armorStack.getItem() instanceof ArmorItem)) { return false; } } ArmorItem helmet = ((ArmorItem)player.getInventory().getArmor(3).getItem()); ArmorItem breastplace = ((ArmorItem)player.getInventory().getArmor(2).getItem()); ArmorItem leggins = ((ArmorItem)player.getInventory().getArmor(1).getItem()); ArmorItem boots = ((ArmorItem)player.getInventory().getArmor(0).getItem()); return helmet.getMaterial() == material && breastplace.getMaterial() == material && leggins.getMaterial() == material && boots.getMaterial() == material; } private boolean hasFullSuitOfArmorOn(Player player){ ItemStack helmet = player.getInventory().getArmor(3); ItemStack breastplace = player.getInventory().getArmor(2); ItemStack leggins = player.getInventory().getArmor(1); ItemStack boots = player.getInventory().getArmor(0); return !helmet.isEmpty() && !breastplace.isEmpty() && !leggins.isEmpty() && !boots.isEmpty(); } } Also when I place two effects on the same armor, the game crashes. Here is the crash file. The code is the same, only this part is different   private static final Map<ArmorMaterial, MobEffectInstance> MATERIAL_TO_EFFECT_MAP = (new ImmutableMap.Builder<ArmorMaterial, MobEffectInstance>()) .put(ModArmorMaterials.EMERALD, new MobEffectInstance(MobEffects.HERO_OF_THE_VILLAGE,200, 1,false,false, true)) .put(ModArmorMaterials.EMERALD, new MobEffectInstance(MobEffects.FIRE_RESISTANCE,200, 1,false,false, true)).build(); I hope you guys can help me. Thanks.
    • I removed all related embeddium and oculus mods, i just tested it by disconnecting and the error happened again. heres the report https://pastebin.com/1kcR5wAt   EDIT: i tried removing xaeros and also smoothboot thinking there may be an issue there, nothing, heres that report too. https://pastebin.com/zQS7i9rM
    • Hi, I need suggestions. I am a beginner in Minecraft Modding. I would like to apply custom effects to some armors, something like: more chance to drop seeds, change zombie awareness, drop more pieces of wood when chopping logs, and things like that. How would you recommend me to do it, is there any library that has something similar and which ones would you recommend me?.
    • "downloading minecraft server failed, invalid Checksum. try again, or manually place server.jar to skip download"    
    • You have to create an Entity class called PlayerPart and use multiple of them to make the different parts of the player. See EnderDragonPart.java source code. The green hitboxes of the dragon are all EnderDragonParts
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.