Jump to content

Recommended Posts

Posted (edited)

Hello,

is it possible to make network/package sending class handler a non static member? When i try to register it as a non-static, errors occur. When all members are static, it works fine.

Is it because NetworkEvent.Context must be static? 

 

Edited part for network example further bellow:

 

Error java.lang.IllegalArgumentException: Registration of network channels is locked

 

Registering message:

//Packet packet = new Packet();   //if handle is non-static

simpleChannel.registerMessage(index++, Packet.class, Packet::encode,
        Packet::new, Packet::handle); //Packet::new, packet::handle;   if handle is non-static

 // Maybe i pass handle wrong, when its non-static?

 

Packet class:

public class Packet{

    private static BlockPos blockPos;

    //public Packet () {};     //For passing handler on non-static

    public Packet(PacketBuffer buffer) {
        Packet.blockPos = buffer.readBlockPos();
    }

    public Packet(BlockPos blockPos) {
        Packet.blockPos = blockPos;
    }

    public void encode(PacketBuffer buffer) {
        buffer.writeBlockPos(Packet.blockPos);
    }

    public static void handle(packetmessage, Supplier<NetworkEvent.Context> contextSupplier) {   //if i make this class non-static, task execution fails

        contextSupplier.get().enqueueWork(() -> {

 

Edit from here: 

So I didnt manage to make methods non static etc..., but I managed to solve this problem by using other stuff, which completely diminished necessity of a non-static handler.

Also, because I didnt manage to find detailed examples or tutorials (apart official documentation on forge website and few posts, which came in handy but coverd mostly/only basics), on how to make network packet system on new minecraft forge (1.14.4) versions, im posting my code here for future people who might stumble on the same problems:

DISCLAIMER: Im not an experienced Minecraft forge mod programmer, nor good programmer in a nutshell, so this code might be non-efficient or have flaws / crashes, especially when testing on DEDICATED_SERVER (tests on LAN worked flawlessly), so read with caution.

 

Registering network packet:

public MainModCLass() {
  
    // Register the setup method for modloading
    FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);

    PacketHandler.registerMessages();  //<--Packet class

}

PacketHandler class:

public class PacketHandler {

    public static String string = "1";  //<--Just a filler string
    
    public static ResourceLocation resourceLocation = new ResourceLocation("mod", "main_channel");    //<--Channel name needs to be unique and cant contain more advanced symbols
    public static ResourceLocation resourceLocation0 = new ResourceLocation("mod", "main_channel0");

    public static final SimpleChannel simpleChannel = NetworkRegistry.ChannelBuilder   //<--Registering channels
            .named(resourceLocation)
            .clientAcceptedVersions(string::equals)
            .serverAcceptedVersions(string::equals)
            .networkProtocolVersion(() -> string)
            .simpleChannel();

    public static final SimpleChannel simpleChannel0 = NetworkRegistry.ChannelBuilder
            .named(resourceLocation0)
            .clientAcceptedVersions(string::equals)
            .serverAcceptedVersions(string::equals)
            .networkProtocolVersion(() -> string)
            .simpleChannel();

    public static void registerMessages() {

        int index = 0;

        simpleChannel.registerMessage(index++, PacketTriggerSEG.class, PacketTriggerSEG::encode,      newhandlesimpleChannel0classnewhandle

PacketTriggerSEG (when the client requests the server for synchronization to begin)

 

public class PacketTriggerSEG {
    
    private BlockPos blockPos;

   public PacketTriggerSEG(PacketBuffer buffer) {
       this.blockPos = buffer.readBlockPos();
    }

    public PacketTriggerSEG(BlockPos blockPos) {
        this.blockPos = blockPos;
    }

    public void encode(PacketBuffer buffer) {
       buffer.writeBlockPos(this.blockPos);
    }

    public static void handle(PacketTriggerSEG message, Supplier<NetworkEvent.Context> contextSupplier) {

        contextSupplier.get().enqueueWork(() -> {                                                                  //<--Adding a thread-safe, future-runnable task for server

            contextSupplier.get().getSender().getServerWorld().getTileEntity(message.blockPos).    
                    getCapability(new UtilCapabilities().UTIL_CAP).ifPresent(st -> {                               //<--Getting server world and finding entity in it with a custom capability assigned to tile entity (from other classes which arent shown here)
                        int tickCounter = st.getCounterForTicks();                                                 //<--getCounterForTicks() - function from manually created custom capability
                        PacketHandler.simpleChannel0.send(PacketDistributor.PLAYER.with(() ->                      //<--Sending packet back to client, to sync value on both sides
                        contextSupplier.get().getSender()), new ValueSynchronizeSEG(message.blockPos, tickCounter));
                    });
        });
        contextSupplier.get().setPacketHandled(true);                                                               //<--Setting packed as handled, so main thread knows its successful and doesnt show warnings/crashes when it completes
    }
}

ValueSynchronizeSEG (when packet of requested info from the server arrives back at the client):

public class ValueSynchronizeSEG {

    private BlockPos blockPos;
    private int tickCounter;

    public ValueSynchronizeSEG(PacketBuffer buffer) {
        this.blockPos = buffer.readBlockPos();
        this.tickCounter = buffer.readInt();
    }

    public ValueSynchronizeSEG(BlockPos blockPos, int tickCounter) {
        this.blockPos = blockPos;
        this.tickCounter = tickCounter;
    }

    public void encode(PacketBuffer buffer) {
        buffer.writeBlockPos(this.blockPos);
        buffer.writeInt(this.tickCounter);
    }

    public static void handle(ValueSynchronizeSEG message, Supplier<NetworkEvent.Context> contextSupplier) {

        contextSupplier.get().enqueueWork(() -> {

            Minecraft.getInstance().world.getTileEntity(message.blockPos).getCapability(new UtilCapabilities().UTIL_CAP).ifPresent(      //<--Setting server side capability values
                    ct -> ct.setCounterForTicks(message.tickCounter));
        });
        contextSupplier.get().setPacketHandled(true);
    }
}

Requesting for packet from only client-side:

private int loop;            <--Simple int to make packets to be sent every second-tick, not every tick

@Override
public void tick() {

        if(loop == 1) {
            PacketHandler.simpleChannel.sendToServer(new PacketTriggerSEG(container.getBlockPos()));
            loop = 0;
        }
        else {
            loop++;
        }
}   //This class is a client-side class, which extends ContainerScreen<YourTileEntityContainerScreenClass> and is efficient, because packets are sent ONLY when GUI is opened by a PlayerEntity.

If you rode all this, I hope it was of some help to you. Enjoy.

Edited by Mr Bonobo
Example of Packet handling - Networking
Posted (edited)

By the way, your thread title is completely useless.

1 hour ago, Mr Bonobo said:

When i try to register it as a non-static, errors occur.

I mean...why do you care? Just leave it static.

Edited by Draco18s

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted (edited)
1 hour ago, Mr Bonobo said:

Error java.lang.IllegalArgumentException: Registration of network channels is locked

You are registering your packets in the wrong place. Where are you registering your packets (when non-static)?

 

1 hour ago, Mr Bonobo said:

private static BlockPos blockPos;

That is not going to work. Packets are not singletons.

A packet is constructed per sending/receiving, and therefore the block pos needs to be an attribute (property?) of the packet object.

Edited by DavidM

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Posted (edited)
1 hour ago, Draco18s said:

By the way, your thread title is completely useless.

I mean...why do you care? Just leave it static.

Thank you for reply, I'm posting by myself first time, so I'm not familiar with this environment.

And non-static is preferable, because I don't want client side to initialize value and use ram when it's not necessary (static values are initialized in both sides, even if I assigned value on server side). So by using non-static value it should be more efficient (if I'm wrong, and it uses ram only when client side requests value from a static member, please correct me, i was using c++ previously, so static and non-static members are kinda new for me)

Edited by Mr Bonobo
Posted (edited)
27 minutes ago, DavidM said:

You are registering your packets in the wrong place. Where are you registering your packets (when non-static)?

 

That is not going to work. Packets are not singletons.

A packet is constructed per sending/receiving, and therefore the block pos needs to be an attribute (property?) of the packet object.

This is where i register packet:

public MyMod() {
    ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.COMMON_CONFIG);
    ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, Config.CLIENT_CONFIG);

    // Register the setup method for modloading
    FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);

    // Register ourselves for server and other game events we are interested in
    Config.loadConfig(Config.COMMON_CONFIG, FMLPaths.CONFIGDIR.get().resolve("mymod-common.toml"));
    Config.loadConfig(Config.CLIENT_CONFIG, FMLPaths.CONFIGDIR.get().resolve("mymod-client.toml"));

//Registering packets here:
    PacketHandler packetHandler = new PacketHandler(); //if non-static class - doesnt work
    packetHandler.registerMessages();

    PacketHandler.registerMessages();   //if static class - works

}

 

And im pretty sure,that BlocPos value isnt a problem, because it worked when everything was static. Though i will test that tomorrow with a simple value. (the code im showing works if its static, but the moment I try to convert everything to non-static and register it as a non-static, it fails to do so).

Edited by Mr Bonobo
Posted (edited)
28 minutes ago, Mr Bonobo said:

And im pretty sure,that BlocPos value isnt a problem, because it worked when everything was static.

It does not. It might appear to be working for you as you either tested it in single player, did an inconclusive test, or got lucky, but making it static is fundamentally broken as it goes against the packet system. In your case, as soon as another packet is constructed in the same JVM before a previous packet is sent, the whole thing breaks.

 

You should not make something "static" just because "I have no idea what the error means; let me just randomly change something and hope it will work"; instead, static should only be used if you want to make something class-specific (probably not the proper definition).

 

32 minutes ago, Mr Bonobo said:

(static values are initialized in both sides, even if I assigned value on server side)

That is only the case if you are playing on a client distribution, where the two sides exist in the same virtual machine. You should never rely on this, as it will break immediately once the mod is installed on the server distribution.

 

28 minutes ago, Mr Bonobo said:

because it worked when everything was static.

Please elaborate. What doesn't work? What is the error it is giving you? There is no concept of "static class" (unless you meant a static subclass, which doesn't seem to be the case here).

Edited by DavidM

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Posted (edited)
40 minutes ago, Mr Bonobo said:

i was using c++ previously, so static and non-static members are kinda new for me

Static in Java is almost exactly like in C++, except for two points (that I can think of):

1. It does not denote the localness of a header member.

2. It cannot be used on a local variable to associate it with the static storage area (as opposed to stack).

Edited by DavidM

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Posted (edited)
18 hours ago, DavidM said:

 

You should not make something "static" just because "I have no idea what the error means; let me just randomly change something and hope it will work"; instead, static should only be used if you want to make something class-specific (probably not the proper definition).

 

Please elaborate. What doesn't work? What is the error it is giving you? There is no concept of "static class" (unless you meant a static subclass, which doesn't seem to be the case here).

Thank you for replies, I made it static and thought its the way to go because only example I stumbled upon on the internet (atleast as new forge versions goes) about packets, handling and creating was with Static Itemhandler on packet class (which is as bad as Static BlockPos if I understood it correctly?)

And yes, its because Im testing everything on singleplayer, and I don't think its possible to do it server-client separate at least with Intelij-gradle.

 

And about other question, I will now post whole code which is non-static, with every single usage / function and try to make it as simple and understandable as possible (I renamed classes/functions/variables):

 

Full error code:

 

Error code {

[22:02:22] [Client thread/ERROR] [ne.mi.fm.ne.NetworkRegistry/NETREGISTRY]: Attempted to register channel mod:main_channel even though registry phase is over
[22:02:22] [Client thread/FATAL] [minecraft/ThreadTaskExecutor]: Error executing task on Client
java.lang.IllegalArgumentException: Registration of network channels is locked
    at net.minecraftforge.fml.network.NetworkRegistry.createInstance(NetworkRegistry.java:130) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.fml.network.NetworkRegistry.access$000(NetworkRegistry.java:49) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.fml.network.NetworkRegistry$ChannelBuilder.createNetworkInstance(NetworkRegistry.java:400) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.fml.network.NetworkRegistry$ChannelBuilder.simpleChannel(NetworkRegistry.java:409) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at com.Vidas.Mod.Packages.PacketHandler.<init>(PacketHandler.java:16) ~[main/:?] {}
    at com.Vidas.Mod.TileEntities.ElectricGeneratorScreen.<init>(ElectricGeneratorScreen.java:48) ~[main/:?] {}
    at net.minecraftforge.fml.network.FMLPlayMessages$OpenContainer.lambda$null$0(FMLPlayMessages.java:287) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at java.util.Optional.ifPresent(Optional.java:159) ~[?:1.8.0_241] {}
    at net.minecraftforge.fml.network.FMLPlayMessages$OpenContainer.lambda$handle$1(FMLPlayMessages.java:284) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.fml.network.NetworkEvent$Context.enqueueWork(NetworkEvent.java:185) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.fml.network.FMLPlayMessages$OpenContainer.handle(FMLPlayMessages.java:282) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.fml.network.simple.IndexedMessageCodec.lambda$tryDecode$3(IndexedMessageCodec.java:114) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at java.util.Optional.ifPresent(Optional.java:159) ~[?:1.8.0_241] {}
    at net.minecraftforge.fml.network.simple.IndexedMessageCodec.tryDecode(IndexedMessageCodec.java:114) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.fml.network.simple.IndexedMessageCodec.consume(IndexedMessageCodec.java:147) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.fml.network.simple.SimpleChannel.networkEventListener(SimpleChannel.java:65) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.eventbus.EventBus.doCastFilter(EventBus.java:212) ~[eventbus-1.0.0-service.jar:?] {}
    at net.minecraftforge.eventbus.EventBus.lambda$addListener$11(EventBus.java:204) ~[eventbus-1.0.0-service.jar:?] {}
    at net.minecraftforge.eventbus.EventBus.post(EventBus.java:258) ~[eventbus-1.0.0-service.jar:?] {}
    at net.minecraftforge.fml.network.NetworkInstance.dispatch(NetworkInstance.java:82) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraftforge.fml.network.NetworkHooks.lambda$onCustomPayload$0(NetworkHooks.java:69) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at java.util.Optional.map(Optional.java:215) ~[?:1.8.0_241] {}
    at net.minecraftforge.fml.network.NetworkHooks.onCustomPayload(NetworkHooks.java:69) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraft.client.network.play.ClientPlayNetHandler.handleCustomPayload(ClientPlayNetHandler.java:1916) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {pl:runtimedistcleaner:A}
    at net.minecraft.network.play.server.SCustomPayloadPlayPacket.processPacket(SCustomPayloadPlayPacket.java:61) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraft.network.play.server.SCustomPayloadPlayPacket.processPacket(SCustomPayloadPlayPacket.java:11) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraft.network.PacketThreadUtil.lambda$checkThreadAndEnqueue$0(PacketThreadUtil.java:19) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraft.util.concurrent.ThreadTaskExecutor.run(ThreadTaskExecutor.java:140) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {pl:accesstransformer:B}
    at net.minecraft.util.concurrent.RecursiveEventLoop.run(RecursiveEventLoop.java:22) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at net.minecraft.util.concurrent.ThreadTaskExecutor.driveOne(ThreadTaskExecutor.java:110) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {pl:accesstransformer:B}
    at net.minecraft.util.concurrent.ThreadTaskExecutor.drainTasks(ThreadTaskExecutor.java:97) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {pl:accesstransformer:B}
    at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:893) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {pl:accesstransformer:B,pl:runtimedistcleaner:A}
    at net.minecraft.client.Minecraft.run(Minecraft.java:384) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {pl:accesstransformer:B,pl:runtimedistcleaner:A}
    at net.minecraft.client.main.Main.main(Main.java:128) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {pl:runtimedistcleaner:A}
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_241] {}
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_241] {}
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_241] {}
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_241] {}
    at net.minecraftforge.userdev.FMLUserdevClientLaunchProvider.lambda$launchService$0(FMLUserdevClientLaunchProvider.java:55) ~[forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
    at cpw.mods.modlauncher.LaunchServiceHandlerDecorator.launch(LaunchServiceHandlerDecorator.java:37) [modlauncher-3.2.0.jar:?] {}
    at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:50) [modlauncher-3.2.0.jar:?] {}
    at cpw.mods.modlauncher.LaunchServiceHandler.launch(LaunchServiceHandler.java:68) [modlauncher-3.2.0.jar:?] {}
    at cpw.mods.modlauncher.Launcher.run(Launcher.java:80) [modlauncher-3.2.0.jar:?] {}
    at cpw.mods.modlauncher.Launcher.main(Launcher.java:65) [modlauncher-3.2.0.jar:?] {}
    at net.minecraftforge.userdev.LaunchTesting.main(LaunchTesting.java:101) [forge-1.14.4-28.1.0_mapped_snapshot_20190719-1.14.3-recomp.jar:?] {}
}

 

Registering PacketHandler class in Main mod class:

public Mod() {
 
PacketHandler packetHandler = new PacketHandler(); 
packetHandler.registerMessages();

}

private void setup(final FMLCommonSetupEvent event) {

//PacketHandler packetHandler = new PacketHandler();
//packetHandler.registerMessages();

} //Disclaimer: I tried it registering in both setup and main constructor - it fails both times here?

 

PacketHandler class:

public class PacketHandler {

    public String string = "1";

    public SimpleChannel simpleChannel = NetworkRegistry.ChannelBuilder     //Creaing SimpleChannel object
            .named(new ResourceLocation("mod", "main_channel"))
            .clientAcceptedVersions(string::equals)
            .serverAcceptedVersions(string::equals)
            .networkProtocolVersion(() -> string)
            .simpleChannel();

    public void registerMessages() {

        int index = 0;
        Packet packet = new Packet ();
        simpleChannel.registerMessage(index++, Packet.class, Packet::encode,
                Packet::new, packet::handle);

 

Packet class: 

public class Packet {


    private BlockPos blockPos;


    public Packet (PacketBuffer buffer) {
        this.blockPos = buffer.readBlockPos();
    }

    public Packet (BlockPos blockPos) {
        this.blockPos = blockPos;
    }

    public Packet () { }          //This constructor is only to create object without any value for PacketHandler class 

    public void encode(PacketBuffer buffer) {
        buffer.writeBlockPos(this.blockPos);
    }

    public void handle(Packet message, Supplier<NetworkEvent.Context> contextSupplier) {

        contextSupplier.get().enqueueWork(() -> {   //Thread-safe zone

            if (contextSupplier.get().getDirection().getOriginationSide().isClient()) {           //this is always CLIENT side

 

Where I try to send packet (and where error occurs):

 

private PacketHandler packetHandler = new PacketHandler();

@Override          //Minecraft-forge implemented class/method for Screen Gui
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {  //Happens every tick, after block container is opened. Only on CLIENT

    packetHandler.simpleChannel.sendToServer(new Packet(container.getBlockPos()));  //Error occurs here

//Further code just for context:
    GlStateManager.color4f(1.0F, 1.0F, 1.0F, 1.0F);
    assert this.minecraft != null;
    this.minecraft.getTextureManager().bindTexture(GUI);
    int relX = (this.width - this.xSize) / 2;
    int relY = (this.height - this.ySize) / 2;

Error code suggests that it cant register, because its unavailable/locked at that phase, so it fails registering first time on game setup? (though i tried searching for keywords with ctrl-f and didnt find any errors)

Also, I tried changing BlockPos to simple Int variable, still same error occured.

Edited by Mr Bonobo
Posted
33 minutes ago, Mr Bonobo said:

Attempted to register channel mod:main_channel even though registry phase is over

This seems pretty self explanatory.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted
4 hours ago, Mr Bonobo said:

Thank you for replies, I made it static and thought its the way to go because only example I stumbled upon on the internet (atleast as new forge versions goes) about packets, handling and creating was with Static Itemhandler on packet class (which is as bad as Static BlockPos if I understood it correctly?)

The packet handler method can be static, as it does not depend on a handler instance (unlike 1.12.2 and before).

 

 

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

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.