Skip to content

Instantly share code, notes, and snippets.

@gigaherz
Last active July 25, 2020 04:12
Show Gist options
  • Save gigaherz/4ad2808f5768ff14c424ca433d8bd58d to your computer and use it in GitHub Desktop.
Save gigaherz/4ad2808f5768ff14c424ca433d8bd58d to your computer and use it in GitHub Desktop.
public static <T extends IModPacket> void registerPacket(SimpleChannel channel, int discriminator, PacketHandler<T> handler)
{
channel.registerMessage(discriminator, handler.getPacketClass(), handler::encode, handler::decode, handler::handle);
}
public static abstract class PacketHandler<T extends IModPacket>
{
private final Class<T> tClass;
protected PacketHandler(Class<T> tClass)
{
this.tClass = tClass;
}
public Class<T> getPacketClass()
{
return tClass;
}
public final void encode(T packet, PacketBuffer buffer)
{
packet.encode(buffer);
}
public final T decode(PacketBuffer buffer)
{
T obj;
try
{
obj = tClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e)
{
throw new RuntimeException("Problem instantiating packet", e);
}
obj.decode(buffer);
return obj;
}
public final void handle(T packet, Supplier<NetworkEvent.Context> context)
{
handleInternal(packet, context);
context.get().setPacketHandled(true);
}
public abstract void handleInternal(T packet, Supplier<NetworkEvent.Context> context);
}
public interface IModPacket
{
void encode(PacketBuffer buffer);
void decode(PacketBuffer buffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment