Jump to content

[1.7.10][Solved] Packet not called or not sending correctly?


Recommended Posts

Posted

I am trying to set a integer in my tile entity from my GUI so I tried to make a packet system. As far as I can tell my packet isn't being called.

 

GUI

package com.robert.instaport.gui;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;

import org.lwjgl.opengl.GL11;

import com.robert.instaport.Instaport;
import com.robert.instaport.common.container.ContainerTeleporter;
import com.robert.instaport.common.tileentity.TileEntityTeleporter;
import com.robert.instaport.lib.Reference;
import com.robert.instaport.packet.TeleporterPacket;

public class GuiTeleporter extends GuiContainer {

	public final int xSizeOfTexture = 176;
	public final int ySizeOfTexture = 228;

	private GuiTextField idField;

	public int id;

	@SuppressWarnings("unused")
	private TileEntityTeleporter tileEntityKeyPad;
	private TileEntityTeleporter tileEntityTeleporter = new TileEntityTeleporter();

        public GuiTeleporter (InventoryPlayer inventoryPlayer, TileEntityTeleporter tileEntity) {
                //the container is instanciated and passed to the superclass for handling
                super(new ContainerTeleporter(inventoryPlayer, tileEntity));
                tileEntityTeleporter = tileEntity;
                this.xSize = xSizeOfTexture;
                this.ySize = ySizeOfTexture;
                TileEntityTeleporter tile = (TileEntityTeleporter) tileEntityTeleporter.getWorldObj().getTileEntity(tileEntityTeleporter.xCoord, tileEntityTeleporter.yCoord, tileEntityTeleporter.zCoord);
                id = tile.getId();
        }

        @Override
        protected void drawGuiContainerForegroundLayer(int param1, int param2) {
        		String title = "Teleporter";
                fontRendererObj.drawString(title, 7, ySize - 220, 4210752);
                fontRendererObj.drawString("Security Card:", 7, ySize - 118, 4210752);
        }
        
        
        
        @SuppressWarnings("unchecked")
	@Override
        public void initGui() {
                super.initGui();
                
                //make buttons
                buttonList.add(new GuiButton(1, width / 2 - 20 / 2 - 60, this.height / 2 - 65, 20, 20, "+"));
                buttonList.add(new GuiButton(2, width / 2 - 20 / 2 + 60, this.height / 2 - 65, 20, 20, "-"));
                buttonList.add(new GuiButton(3, width / 2 - 100 / 2, this.height / 2 - 35, 100, 20, "Save"));

                idField = new GuiTextField(fontRendererObj, this.width / 2 - 70 / 2, this.height / 2 - 65, 70, 20);
                idField.setFocused(false);
                idField.setMaxStringLength(10);
        }
        
        public void updateScreen() {
        	idField.setText(Integer.toString(id));
        }
        
        public void drawScreen(int i, int j, float f) {
        	super.drawScreen(i, j, f);
        	idField.drawTextBox();

        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream(;
        DataOutputStream outputStream = new DataOutputStream(bos);

	protected void actionPerformed(GuiButton guibutton) {
            switch(guibutton.id) {
                case 1://add
                	id += 1;
                    break;
                case 2:// subtract
                	if(!(id <= 0)) id -= 1;
                	break;
                case 3://save
                	Instaport.packetPipeline.sendToServer(new TeleporterPacket(tileEntityTeleporter.xCoord, tileEntityTeleporter.yCoord, tileEntityTeleporter.zCoord, id));
            	}
                //Packet code here
                //PacketDispatcher.sendPacketToServer(packet); //send packet
        }
        
        ResourceLocation texture = new ResourceLocation(Reference.MOD_ID.toLowerCase() + ":" + "textures/gui/Teleporter.png");
        @Override
        protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
        		
                GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
                //this.mc.renderEngine.bindTexture(texture);
                this.mc.getTextureManager().bindTexture(texture);
                int x = (width - xSizeOfTexture) / 2;
                int y = (height - ySizeOfTexture) / 2;
                this.drawTexturedModalRect(x, y, 0, 0, xSizeOfTexture, ySizeOfTexture);
        }

}

 

TileEntity

package com.robert.instaport.common.tileentity;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;

public class TileEntityTeleporter extends TileEntity implements IInventory {

        private ItemStack[] inv;

	public int detectionRange;
        
    	public static int id;

	public TileEntityTeleporter(){
                inv = new ItemStack[1];
        }

    public void setInvalid() {
        worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2);
    }
        
        @Override
        public int getSizeInventory() {
                return inv.length;
        }

        @Override
        public ItemStack getStackInSlot(int slot) {
                return inv[slot];
        }

        @Override
        public Packet getDescriptionPacket() {
        	NBTTagCompound tag = new NBTTagCompound();
        	this.writeToNBT(tag);
        	return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tag);
        }

        @Override
        public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet) {
        	readFromNBT(packet.func_148857_g());
        }

        @Override
        public void setInventorySlotContents(int slot, ItemStack stack) {
                inv[slot] = stack;
                if (stack != null && stack.stackSize > getInventoryStackLimit()) {
                        stack.stackSize = getInventoryStackLimit();
                }
        }

        @Override
        public ItemStack decrStackSize(int slot, int amt) {
                ItemStack stack = getStackInSlot(slot);
                if (stack != null) {
                        if (stack.stackSize <= amt) {
                                setInventorySlotContents(slot, null);
                        } else {
                                stack = stack.splitStack(amt);
                                if (stack.stackSize == 0) {
                                        setInventorySlotContents(slot, null);
                                }
                        }
                }
                return stack;
        }

        @Override
        public ItemStack getStackInSlotOnClosing(int slot) {
                ItemStack stack = getStackInSlot(slot);
                if (stack != null) {
                        setInventorySlotContents(slot, null);
                }
                return stack;
        }
        
        @Override
        public int getInventoryStackLimit() {
                return 1;
        }

        @Override
        public boolean isUseableByPlayer(EntityPlayer player) {
                return worldObj.getTileEntity(xCoord, yCoord, zCoord) == this &&
                player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) < 64;
        }
        
        @Override
        public void readFromNBT(NBTTagCompound tagCompound) {
                super.readFromNBT(tagCompound);
                NBTTagList tagList = tagCompound.getTagList("Inventory", 10);
                for (int i = 0; i < tagList.tagCount(); i++) {
                        NBTTagCompound tag = (NBTTagCompound) tagList.getCompoundTagAt(i);
                        byte slot = tag.getByte("Slot");
                        if (slot >= 0 && slot < inv.length) {
                                inv[slot] = ItemStack.loadItemStackFromNBT(tag);
                        }
                }
                  
        }
        @Override
        public void writeToNBT(NBTTagCompound tagCompound) {
                super.writeToNBT(tagCompound);
                
                NBTTagList itemList = new NBTTagList();
                for (int i = 0; i < inv.length; i++) {
                        ItemStack stack = inv[i];
                        if (stack != null) {
                                NBTTagCompound tag = new NBTTagCompound();
                                tag.setByte("Slot", (byte) i);
                                stack.writeToNBT(tag);
                                itemList.appendTag(tag);
                        }
                }
                tagCompound.setTag("Inventory", itemList);

        }
        
        public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
        
	@Override
	public String getInventoryName() {
		return null;
	}

	@Override
	public boolean hasCustomInventoryName() {
		return false;
	}

	@Override
	public void openInventory() {					
	}

	@Override
	public void closeInventory() {
	}

	@Override
	public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_) {
		return false;
	}

	public void setDetectionRange(int _range) {

	}
}

 

PacketPipeline(From NettyPacket Handler tutorial)

package com.robert.instaport.packet;

import java.util.*;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.INetHandler;
import net.minecraft.network.NetHandlerPlayServer;

import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.FMLEmbeddedChannel;
import cpw.mods.fml.common.network.FMLOutboundHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

/**
* Packet pipeline class. Directs all registered packet data to be handled by the packets themselves.
* @author sirgingalot
* some code from: cpw
*/
@ChannelHandler.Sharable
public class PacketPipeline extends MessageToMessageCodec<FMLProxyPacket, AbstractPacket> {

    private EnumMap<Side, FMLEmbeddedChannel>           channels;
    private LinkedList<Class<? extends AbstractPacket>> packets           = new LinkedList<Class<? extends AbstractPacket>>();
    private boolean                                     isPostInitialised = false;

    /**
     * Register your packet with the pipeline. Discriminators are automatically set.
     *
     * @param clazz the class to register
     *
     * @return whether registration was successful. Failure may occur if 256 packets have been registered or if the registry already contains this packet
     */
    public boolean registerPacket(Class<? extends AbstractPacket> clazz) {
        if (this.packets.size() > 256) {
            // You should log here!!
            return false;
        }

        if (this.packets.contains(clazz)) {
            // You should log here!!
            return false;
        }

        if (this.isPostInitialised) {
            // You should log here!!
            return false;
        }

        this.packets.add(clazz);
        return true;
    }

    // In line encoding of the packet, including discriminator setting
    @Override
    protected void encode(ChannelHandlerContext ctx, AbstractPacket msg, List<Object> out) throws Exception {
        ByteBuf buffer = Unpooled.buffer();
        Class<? extends AbstractPacket> clazz = msg.getClass();
        if (!this.packets.contains(msg.getClass())) {
            throw new NullPointerException("No Packet Registered for: " + msg.getClass().getCanonicalName());
        }

        byte discriminator = (byte) this.packets.indexOf(clazz);
        buffer.writeByte(discriminator);
        msg.encodeInto(ctx, buffer);
        FMLProxyPacket proxyPacket = new FMLProxyPacket(buffer.copy(), ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get());
        out.add(proxyPacket);
    }

    // In line decoding and handling of the packet
    @Override
    protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception {
        ByteBuf payload = msg.payload();
        byte discriminator = payload.readByte();
        Class<? extends AbstractPacket> clazz = this.packets.get(discriminator);
        if (clazz == null) {
            throw new NullPointerException("No packet registered for discriminator: " + discriminator);
        }

        AbstractPacket pkt = clazz.newInstance();
        pkt.decodeInto(ctx, payload.slice());

        EntityPlayer player;
        switch (FMLCommonHandler.instance().getEffectiveSide()) {
            case CLIENT:
                player = this.getClientPlayer();
                pkt.handleClientSide(player);
                break;

            case SERVER:
                INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
                player = ((NetHandlerPlayServer) netHandler).playerEntity;
                pkt.handleServerSide(player);
                break;

            default:
        }

        out.add(pkt);
    }

    // Method to call from FMLInitializationEvent
    public void initialise() {
        this.channels = NetworkRegistry.INSTANCE.newChannel("INSTAPORT", this);
    }

    // Method to call from FMLPostInitializationEvent
    // Ensures that packet discriminators are common between server and client by using logical sorting
    public void postInitialise() {
        if (this.isPostInitialised) {
            return;
        }

        this.isPostInitialised = true;
        Collections.sort(this.packets, new Comparator<Class<? extends AbstractPacket>>() {

            @Override
            public int compare(Class<? extends AbstractPacket> clazz1, Class<? extends AbstractPacket> clazz2) {
                int com = String.CASE_INSENSITIVE_ORDER.compare(clazz1.getCanonicalName(), clazz2.getCanonicalName());
                if (com == 0) {
                    com = clazz1.getCanonicalName().compareTo(clazz2.getCanonicalName());
                }

                return com;
            }
        });
    }

    @SideOnly(Side.CLIENT)
    private EntityPlayer getClientPlayer() {
        return Minecraft.getMinecraft().thePlayer;
    }

    /**
     * Send this message to everyone.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message The message to send
     */
    public void sendToAll(AbstractPacket message) {
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
        this.channels.get(Side.SERVER).writeAndFlush(message);
    }

    /**
     * Send this message to the specified player.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message The message to send
     * @param player  The player to send it to
     */
    public void sendTo(AbstractPacket message, EntityPlayerMP player) {
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
        this.channels.get(Side.SERVER).writeAndFlush(message);
    }

    /**
     * Send this message to everyone within a certain range of a point.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message The message to send
     * @param point   The {@link cpw.mods.fml.common.network.NetworkRegistry.TargetPoint} around which to send
     */
    public void sendToAllAround(AbstractPacket message, NetworkRegistry.TargetPoint point) {
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point);
        this.channels.get(Side.SERVER).writeAndFlush(message);
    }

    /**
     * Send this message to everyone within the supplied dimension.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message     The message to send
     * @param dimensionId The dimension id to target
     */
    public void sendToDimension(AbstractPacket message, int dimensionId) {
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION);
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimensionId);
        this.channels.get(Side.SERVER).writeAndFlush(message);
    }

    /**
     * Send this message to the server.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message The message to send
     */
    public void sendToServer(AbstractPacket message) {
        this.channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
        this.channels.get(Side.CLIENT).writeAndFlush(message);
    }
}

 

Packet

package com.robert.instaport.packet;

import com.robert.instaport.common.tileentity.TileEntityTeleporter;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.ByteBufUtils;

public class TeleporterPacket extends AbstractPacket
{

    private int x, y, z;
    private int id;

    public TeleporterPacket()
    {
    }

    public TeleporterPacket(int x, int y, int z, int ids)
    {
        this.x = x;
        this.y = y;
        this.z = z;
        this.id = ids;
    }

    @Override
    public void encodeInto (ChannelHandlerContext ctx, ByteBuf buffer)
    {
        buffer.writeInt(x);
        buffer.writeInt(y);
        buffer.writeInt(z);
        ByteBufUtils.writeUTF8String(buffer, Integer.toString(id));
    }

    @Override
    public void decodeInto (ChannelHandlerContext ctx, ByteBuf buffer)
    {
        x = buffer.readInt();
        y = buffer.readInt();
        z = buffer.readInt();
        id = Integer.parseInt(ByteBufUtils.readUTF8String(buffer));
    }

    @Override
    public void handleClientSide (EntityPlayer player)
    {
    }

    @Override
    public void handleServerSide (EntityPlayer player)
    {
        World world = player.worldObj;
        TileEntity te = world.getTileEntity(x, y, z);

        if (te instanceof TileEntityTeleporter)
        {
            ((TileEntityTeleporter) te).setId(id);
            System.out.println("Set id");
        }
        if (te instanceof TileEntityTeleporter)
        {
            ((TileEntityTeleporter) te).setId(id);
            System.out.println("Set id");
        }
    }

}

Posted

You should use SimpleNetworkWrapper.

 

If you insist on the old code, it looks like you didn't register your packet and initialize + post-initialize the pipeline.

I actually did use the initialize and post initialize for the pipeline however i didn't register the packet im going to try that now. I know about the old code thing but I just couldn't get the simple network wrapper to work so I figured I would get it working the old way then later down the road change to the simple network wrapper. Thanks for the help.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.