Skip to content

Instantly share code, notes, and snippets.

@CatDany
Last active June 28, 2022 21:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CatDany/4a3df7fcb3c8270cf70b to your computer and use it in GitHub Desktop.
Save CatDany/4a3df7fcb3c8270cf70b to your computer and use it in GitHub Desktop.
Packets are Easy (by Dany)
@EventHandler
public static void init(FMLInitializationEvent e)
{
// this should be in initialization
PacketHandler.initPackets();
}
public class PacketHandler
{
public static SimpleNetworkWrapper net;
public static void initPackets()
{
net = NetworkRegistry.INSTANCE.newSimpleChannel("YourModId".toUpperCase());
registerMessage(SimplePacket.class, SimplePacket.SimpleMessage.class);
}
private static int nextPacketId = 0;
private static void registerMessage(Class packet, Class message)
{
net.registerMessage(packet, message, nextPacketId, Side.CLIENT);
net.registerMessage(packet, message, nextPacketId, Side.SERVER);
nextPacketId++;
}
}
public class SimplePacket implements IMessageHandler<SimpleMessage, IMessage>
{
@Override
public IMessage onMessage(SimpleMessage message, MessageContext ctx)
{
// just to make sure that the side is correct
if (ctx.side.isClient())
{
int integer = message.simpleInt;
boolean bool = message.simpleBool;
}
}
public static class SimpleMessage implements IMessage
{
private int simpleInt;
private boolean simpleBool;
// this constructor is required otherwise you'll get errors (used somewhere in fml through reflection)
public SimpleMessage() {}
public SimpleMessage(int simpleInt, boolean simpleBool)
{
this.simpleInt = simpleInt;
this.simpleBool = simpleBool;
}
@Override
public void fromBytes(ByteBuf buf)
{
// the order is important
this.simpleInt = buf.readInt();
this.simpleBool = buf.readBoolean();
}
@Override
public void toBytes(ByteBuf buf)
{
buf.writeInt(simpleInt);
buf.writeBoolean(simpleBool);
}
}
}
// Sending packet to server
IMessage msg = new SimplePacket.SimpleMessage(500, true);
PacketHandler.net.sendToServer(msg);
// Sending packet to client
if (player instanceof EntityPlayerMP)
{
IMessage msg = new SimplePacket.SimpleMessage(800, false);
PacketHandler.net.sendTo(msg, (EntityPlayerMP)player);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment