Skip to content

Instantly share code, notes, and snippets.

@RainWarrior
Last active August 29, 2015 14:02
Show Gist options
  • Save RainWarrior/8bb1acb09f9fa23bdbd5 to your computer and use it in GitHub Desktop.
Save RainWarrior/8bb1acb09f9fa23bdbd5 to your computer and use it in GitHub Desktop.
package com.examplemod.network;
import io.netty.buffer.ByteBuf;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
public class ExampleMessageHandler implements IMessageHandler<ExampleMessageHandler.ExampleMessage, IMessage> {
public ExampleMessageHandler() {} // needed for FML to be able to create instances of this handler
@Override
public IMessage onMessage(ExampleMessage message, MessageContext context)
{
// this example is for server handler
if(!context.side.isServer())
throw new IllegalStateException("received ExampleMessage " + message + "on client side!");
World world = context.getServerHandler().playerEntity.worldObj;
// World world = Minecraft.getMinecraft().theWorld; // on the client
world.markBlockForUpdate(message.x, message.y, message.z); // or whatever
return null; // no reply
}
public static class ExampleMessage implements IMessage {
public int x, y, z;
public ExampleMessage() {} // needed for Netty to create instances to read into
public ExampleMessage(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
@Override
public void fromBytes(ByteBuf buf)
{
x = buf.readInt();
y = buf.readInt();
z = buf.readInt();
}
@Override
public void toBytes(ByteBuf buf)
{
buf.writeInt(x);
buf.writeInt(y);
buf.writeInt(z);
}
}
}
// somewhere convenient
public static SimpleNetworkWrapper netHandler = NetworkRegistry.INSTANCE.newSimpleChannel(modId + "|B"); //doesn't have to have this suffix, just an example
// call sometime before using network stuff
// 0 should be unique per message - they're dispatched that way
// side is the receiving side - the side where onMessage will be called
netHandler.registerMessage(ExampleMessageHandler.class, ExampleMessageHandler.ExampleMessage.class, 0, Side.SERVER);
// to send a packet to server:
netHandler.sendToServer(message);
// look inside SimpleNetworkWrapper class for additional send methods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment