Skip to content

Instantly share code, notes, and snippets.

@firstspring1845
Last active August 29, 2015 14:17
Show Gist options
  • Save firstspring1845/1b2fe06402539aa2bc93 to your computer and use it in GitHub Desktop.
Save firstspring1845/1b2fe06402539aa2bc93 to your computer and use it in GitHub Desktop.
NBTMessageHandler継承してhandle実装したクラス作ってインスタンスをNBTMessageHandler#setHandlerで設定
後はパケット投げたい所でNBT作ってNBTMessageHandler.handler使って投げるだけです
細かい部分は察して
package net.firsp.lib.packet;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import java.io.ByteArrayInputStream;
public class NBTMessage implements IMessage {
NBTTagCompound nbt;
public NBTMessage(String channel, NBTTagCompound nbt){
this.nbt = new NBTTagCompound();
nbt.setString("channel", channel);
nbt.setTag("tag", nbt);
}
public NBTMessage(){
}
public NBTTagCompound getNBT(){
return nbt;
}
@Override
public void fromBytes(ByteBuf buf) {
try{
byte[] arr = new byte[buf.readInt()];
buf.readBytes(arr);
nbt = CompressedStreamTools.readCompressed(new ByteArrayInputStream(arr));
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public void toBytes(ByteBuf buf) {
try{
byte[] arr = CompressedStreamTools.compress(nbt);
buf.writeInt(arr.length);
buf.writeBytes(arr);
}catch(Exception e){
e.printStackTrace();
}
}
}
package net.firsp.lib.packet;
import com.google.common.collect.Maps;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.nbt.NBTTagCompound;
import java.util.Map;
public class NBTMessageHandler implements IMessageHandler<NBTMessage, IMessage> {
public static final SimpleNetworkWrapper handler = NetworkRegistry.INSTANCE.newSimpleChannel("NBTPacket");
private static final Map<String,NBTMessageHandler> handlers = Maps.newHashMap();
public static void setHandler(String channel, NBTMessageHandler handler){
handlers.put(channel, handler);
}
static{
handler.registerMessage(NBTMessageHandler.class, NBTMessage.class, 0, Side.CLIENT);
handler.registerMessage(NBTMessageHandler.class, NBTMessage.class, 1, Side.SERVER);
}
@Override
public IMessage onMessage(NBTMessage message, MessageContext ctx) {
NBTTagCompound tag = message.getNBT();
String channel = tag.getString("channel");
if(handlers.containsKey(channel)){
return handlers.get(channel).handle(tag.getCompoundTag("tag"), ctx);
}
return null;
}
public IMessage handle(NBTTagCompound tag, MessageContext ctx){
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment