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



×
×
  • Create New...

Important Information

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