Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[SOLVED]-kinda Packet handler / Simple channel


Mr Bonobo
 Share

Recommended Posts

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
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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
Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
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.

 Share



  • Recently Browsing

    No registered users viewing this page.

  • Posts

    • Whenever i logout and back-in in the game, the data resets to its define state (how can i save the entity data to be persistent)   the code words, data is used flawlessly, but just doesn't save through game exit public class TyBoss extends Monster{ public static final EntityDataAccessor<Boolean> STILL_HOSTILE = SynchedEntityData.defineId(TyBoss.class, EntityDataSerializers.BOOLEAN); private static final EntityDataAccessor<Byte> SCOUNT_TAG = SynchedEntityData.defineId(TyBoss.class, EntityDataSerializers.BYTE); (...) protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(SCOUNT_TAG, (byte) 0); this.entityData.define(STILL_HOSTILE, true); } (...) public void startSeenByPlayer(ServerPlayer p_01_) { super.startSeenByPlayer(p_01_); if (this.entityData.get(STILL_HOSTILE)) { this.bossEvent.addPlayer(p_01_);} } public void stopSeenByPlayer(ServerPlayer p_01_) { super.stopSeenByPlayer(p_01_); this.bossEvent.removePlayer(p_01_); } (...) }  
    • Error downloading These libraries failed to download. Try again. org.scala-lang.plugins.scala-continuations-library_2.11:1.0.2 org.scala-lang.plugins.scala-continuations-plugin_2.11.1:1.0.2  
    • file:///C:/Users/chinc/Downloads/forge-1.17.1-37.0.103-installer.jar.log
    • ---- Minecraft Crash Report ---- // Who set us up the TNT? Time: 10/24/21, 8:51 PM Description: Initializing game org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError: An unexpected critical error was encountered     at org.spongepowered.asm.mixin.transformer.MixinProcessor.applyMixins(MixinProcessor.java:363)     at org.spongepowered.asm.mixin.transformer.MixinTransformer.transformClass(MixinTransformer.java:208)     at org.spongepowered.asm.mixin.transformer.MixinTransformer.transformClassBytes(MixinTransformer.java:178)     at org.spongepowered.asm.mixin.transformer.FabricMixinTransformerProxy.transformClassBytes(FabricMixinTransformerProxy.java:23)     at meteordevelopment.meteorclient.MixinPlugin$Transformer.transformClassBytes(MixinPlugin.java:37)     at net.fabricmc.loader.launch.knot.KnotClassDelegate.getPostMixinClassByteArray(KnotClassDelegate.java:162)     at net.fabricmc.loader.launch.knot.KnotClassLoader.loadClass(KnotClassLoader.java:154)     at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)     at net.minecraft.class_757.<init>(class_757.java:283)     at net.minecraft.class_310.<init>(class_310.java:565)     at net.minecraft.client.main.Main.main(Main.java:179)     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     at java.base/java.lang.reflect.Method.invoke(Method.java:567)     at net.fabricmc.loader.game.MinecraftGameProvider.launch(MinecraftGameProvider.java:234)     at net.fabricmc.loader.launch.knot.Knot.launch(Knot.java:153)     at net.fabricmc.loader.launch.knot.KnotClient.main(KnotClient.java:28) Caused by: org.spongepowered.asm.mixin.injection.throwables.InjectionError: Critical injection failure: Redirector updateHasStatusEffectProxy(Lnet/minecraft/class_746;Lnet/minecraft/class_1291;)Z in meteor-client.mixins.json:LightmapTextureManagerMixin failed injection check, (0/1) succeeded. Scanned 1 target(s). Using refmap meteor-client-refmap.json     at org.spongepowered.asm.mixin.injection.struct.InjectionInfo.postInject(InjectionInfo.java:408)     at org.spongepowered.asm.mixin.transformer.MixinTargetContext.applyInjections(MixinTargetContext.java:1291)     at org.spongepowered.asm.mixin.transformer.MixinApplicatorStandard.applyInjections(MixinApplicatorStandard.java:1042)     at org.spongepowered.asm.mixin.transformer.MixinApplicatorStandard.applyMixin(MixinApplicatorStandard.java:395)     at org.spongepowered.asm.mixin.transformer.MixinApplicatorStandard.apply(MixinApplicatorStandard.java:320)     at org.spongepowered.asm.mixin.transformer.TargetClassContext.applyMixins(TargetClassContext.java:345)     at org.spongepowered.asm.mixin.transformer.MixinProcessor.applyMixins(MixinProcessor.java:569)     at org.spongepowered.asm.mixin.transformer.MixinProcessor.applyMixins(MixinProcessor.java:351)     ... 17 more A detailed walkthrough of the error, its code path and all known details is as follows: --------------------------------------------------------------------------------------- -- Head -- Thread: Render thread Stacktrace:     at org.spongepowered.asm.mixin.transformer.MixinProcessor.applyMixins(MixinProcessor.java:363)     at org.spongepowered.asm.mixin.transformer.MixinTransformer.transformClass(MixinTransformer.java:208)     at org.spongepowered.asm.mixin.transformer.MixinTransformer.transformClassBytes(MixinTransformer.java:178)     at org.spongepowered.asm.mixin.transformer.FabricMixinTransformerProxy.transformClassBytes(FabricMixinTransformerProxy.java:23)     at meteordevelopment.meteorclient.MixinPlugin$Transformer.transformClassBytes(MixinPlugin.java:37)     at net.fabricmc.loader.launch.knot.KnotClassDelegate.getPostMixinClassByteArray(KnotClassDelegate.java:162)     at net.fabricmc.loader.launch.knot.KnotClassLoader.loadClass(KnotClassLoader.java:154)     at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)     at net.minecraft.class_757.<init>(class_757.java:283)     at net.minecraft.class_310.<init>(class_310.java:565) -- Initialization -- Details: Stacktrace:     at net.minecraft.client.main.Main.main(Main.java:179)     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     at java.base/java.lang.reflect.Method.invoke(Method.java:567)     at net.fabricmc.loader.game.MinecraftGameProvider.launch(MinecraftGameProvider.java:234)     at net.fabricmc.loader.launch.knot.Knot.launch(Knot.java:153)     at net.fabricmc.loader.launch.knot.KnotClient.main(KnotClient.java:28) -- System Details -- Details:     Minecraft Version: 1.17.1     Minecraft Version ID: 1.17.1     Operating System: Windows 10 (amd64) version 10.0     Java Version: 16.0.1, Microsoft     Java VM Version: OpenJDK 64-Bit Server VM (mixed mode), Microsoft     Memory: 653549032 bytes (623 MiB) / 1778384896 bytes (1696 MiB) up to 2147483648 bytes (2048 MiB)     CPUs: 12     Processor Vendor: AuthenticAMD     Processor Name: AMD Ryzen 5 3600 6-Core Processor                   Identifier: AuthenticAMD Family 23 Model 113 Stepping 0     Microarchitecture: Zen 2     Frequency (GHz): 3.59     Number of physical packages: 1     Number of physical CPUs: 6     Number of logical CPUs: 12     Graphics card #0 name: Radeon RX 580 Series     Graphics card #0 vendor: Advanced Micro Devices, Inc. (0x1002)     Graphics card #0 VRAM (MB): 4095.00     Graphics card #0 deviceId: 0x67df     Graphics card #0 versionInfo: DriverVersion=27.20.22025.1006     Memory slot #0 capacity (MB): 8192.00     Memory slot #0 clockSpeed (GHz): 2.40     Memory slot #0 type: DDR4     Virtual memory max (MB): 30651.30     Virtual memory used (MB): 17073.36     Swap memory total (MB): 22528.00     Swap memory used (MB): 1513.81     JVM Flags: 9 total; -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump -Xss1M -Xmx2G -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:G1NewSizePercent=20 -XX:G1ReservePercent=20 -XX:MaxGCPauseMillis=50 -XX:G1HeapRegionSize=32M     Fabric Mods:          apoli: Apoli 2.0.3         baritone: Baritone 1.7.0         calio: Calio 1.0.3         cardinal-components-base: Cardinal Components API (base) 3.1.1         cardinal-components-entity: Cardinal Components API (entities) 3.1.1         cloth-basic-math: Cloth Basic Math 0.5.1         cloth-config2: Cloth Config v4 5.0.34         fabric: Fabric API 0.41.0+1.17         fabric-api-base: Fabric API Base 0.3.0+a02b446318         fabric-api-lookup-api-v1: Fabric API Lookup API (v1) 1.3.0+cbda931818         fabric-biome-api-v1: Fabric Biome API (v1) 3.2.0+cbda931818         fabric-blockrenderlayer-v1: Fabric BlockRenderLayer Registration (v1) 1.1.5+a02b446318         fabric-command-api-v1: Fabric Command API (v1) 1.1.3+5ab9934c18         fabric-commands-v0: Fabric Commands (v0) 0.2.2+92519afa18         fabric-containers-v0: Fabric Containers (v0) 0.1.12+cbda931818         fabric-content-registries-v0: Fabric Content Registries (v0) 0.3.0+cbda931818         fabric-crash-report-info-v1: Fabric Crash Report Info (v1) 0.1.5+be9da31018         fabric-dimensions-v1: Fabric Dimensions API (v1) 2.0.11+6cefd57718         fabric-entity-events-v1: Fabric Entity Events (v1) 1.3.0+57bef5a318         fabric-events-interaction-v0: Fabric Events Interaction (v0) 0.4.10+fc40aa9d18         fabric-events-lifecycle-v0: Fabric Events Lifecycle (v0) 0.2.1+92519afa18         fabric-game-rule-api-v1: Fabric Game Rule API (v1) 1.0.7+cbda931818         fabric-item-api-v1: Fabric Item API (v1) 1.2.4+cbda931818         fabric-item-groups-v0: Fabric Item Groups (v0) 0.2.10+b7ab612118         fabric-key-binding-api-v1: Fabric Key Binding API (v1) 1.0.4+cbda931818         fabric-keybindings-v0: Fabric Key Bindings (v0) 0.2.2+36b77c3e18         fabric-lifecycle-events-v1: Fabric Lifecycle Events (v1) 1.4.4+a02b446318         fabric-loot-tables-v1: Fabric Loot Tables (v1) 1.0.4+a02b446318         fabric-mining-levels-v0: Fabric Mining Levels (v0) 0.1.3+92519afa18         fabric-models-v0: Fabric Models (v0) 0.3.0+a02b446318         fabric-networking-api-v1: Fabric Networking API (v1) 1.0.13+cbda931818         fabric-networking-blockentity-v0: Fabric Networking Block Entity (v0) 0.2.11+a02b446318         fabric-networking-v0: Fabric Networking (v0) 0.3.2+92519afa18         fabric-object-builder-api-v1: Fabric Object Builder API (v1) 1.10.9+cbda931818         fabric-object-builders-v0: Fabric Object Builders (v0) 0.7.3+a02b446318         fabric-particles-v1: Fabric Particles (v1) 0.2.4+a02b446318         fabric-registry-sync-v0: Fabric Registry Sync (v0) 0.7.11+7931163218         fabric-renderer-api-v1: Fabric Renderer API (v1) 0.4.4+cbda931818         fabric-renderer-indigo: Fabric Renderer - Indigo 0.4.8+cbda931818         fabric-renderer-registries-v1: Fabric Renderer Registries (v1) 3.2.4+7931163218         fabric-rendering-data-attachment-v1: Fabric Rendering Data Attachment (v1) 0.1.5+a02b446318         fabric-rendering-fluids-v1: Fabric Rendering Fluids (v1) 0.1.14+4658223018         fabric-rendering-v0: Fabric Rendering (v0) 1.1.5+7931163218         fabric-rendering-v1: Fabric Rendering (v1) 1.9.0+7931163218         fabric-resource-loader-v0: Fabric Resource Loader (v0) 0.4.8+a00e834b18         fabric-screen-api-v1: Fabric Screen API (v1) 1.0.4+cbda931818         fabric-screen-handler-api-v1: Fabric Screen Handler API (v1) 1.1.8+cbda931818         fabric-structure-api-v1: Fabric Structure API (v1) 1.1.13+5ab9934c18         fabric-tag-extensions-v0: Fabric Tag Extensions (v0) 1.2.1+b06cb95b18         fabric-textures-v0: Fabric Textures (v0) 1.0.6+a02b446318         fabric-tool-attribute-api-v1: Fabric Tool Attribute API (v1) 1.2.12+b7ab612118         fabric-transfer-api-v1: Fabric Transfer API (v1) 1.4.0+7931163218         fabricloader: Fabric Loader 0.11.7         fallflyinglib: FallFlyingLib 3.0.0-beta.2         java: OpenJDK 64-Bit Server VM 16         meteor-client: Meteor Client 0.4.5         minecraft: Minecraft 1.17.1         origins: Origins 1.1.2         playerabilitylib: Pal 1.3.0-nightly.1.17-rc1         reach-entity-attributes: Reach Entity Attributes 2.1.1     Launched Version: fabric-loader-0.11.7-1.17.1     Backend library: LWJGL version 3.2.2 build 10     Backend API: Radeon RX 580 Series GL version 3.2.14742 Core Profile Forward-Compatible Context 21.8.2 27.20.22025.1006, ATI Technologies Inc.     Window size: <not initialized>     GL Caps: Using framebuffer using OpenGL 3.2     GL debug messages:      Using VBOs: Yes     Is Modded: Definitely; Client brand changed to 'fabric'     Type: Client (map_client.txt)     CPU: 12x AMD Ryzen 5 3600 6-Core Processor 
    • If you want the more future proof in-code solution that doesn't require an arbitrary hardcoded string interpolation,   .withStyle(ChatFormatting.GOLD) this call on the `TextComponent` will color it. You can use any ChatFormatting enum constant, including ones that are added after the fact, and you don't have to consult some table on the internet to find what you want.
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.