Created
July 8, 2014 21:03
-
-
Save CatDany/9dc33b0eecc259ce5760 to your computer and use it in GitHub Desktop.
Such Network, Very Packet, Much Handler For So 1.7.2 / 1.7.10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// PacketHandler.java /// | |
public class PacketHandler | |
{ | |
public static PacketHandler instance; | |
public final SimpleNetworkWrapper net; | |
public static void init() | |
{ | |
instance = new PacketHandler(); | |
instance.net = NetworkRegistry.INSTANCE.newSimpleChannel("CHANNEL_NAME_USE_YOUR_MODID"); | |
registerPacket(0, TestPacket.class, TestPacket.TestMessage.class); | |
} | |
private void registerPacket(int index, Class packet, Class message) | |
{ | |
net.registerMessage(packet, message, index, Side.CLIENT); | |
} | |
} | |
/// TestPacket.java /// | |
public class TestPacket implements IMessageHandler<TestMessage, IMessage> | |
{ | |
// This calls when a client or a server receives a message, after fromBytes() | |
@Override | |
public IMessage onMessage(FlyMessage message, MessageContext ctx) | |
{ | |
if (ctx.side.isClient()) | |
{ | |
System.out.println("Hello, I sent you a message with a byte. Byte = " + message.exampleByte); | |
} | |
// You can return reply message if you want, null for nothing | |
return null; | |
} | |
public static class TestMessage implements IMessage | |
{ | |
private byte exampleByte; | |
@Override | |
public void fromBytes(ByteBuf buf) | |
{ | |
this.exampleByte = buf.readByte(); | |
} | |
@Override | |
public void toBytes(ByteBuf buf) | |
{ | |
buf.writeByte(exampleByte); | |
} | |
public FlyMessage setByte(byte par1) | |
{ | |
this.exampleByte = par1; | |
return this; | |
} | |
} | |
} | |
/// Sending a packet /// | |
// always check for "instanceof" when casting something | |
if (player instanceof EntityPlayerMP) | |
{ | |
PacketHandler.instance.net.sendTo(new TestMessage().setByte(255), (EntityPlayerMP)player); | |
} | |
/** | |
* you can send packets from client to server the similar way | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment