Jump to content

How to actually attach variables/information to server-to-client packets?


mintmeal

Recommended Posts

I'm relatively new to all of this and sure the answer to this is very simple, yet I can't seem to find any answers within the documentation or these forums. I (working in 1.19.2) am trying to write a system of packets to make it so that, when an item is used by one user, it creates particles that are seen by all nearby players. These particles should spawn at the position of the player who uses the items. Right now I have a packet, "ParticlePacket", that is sent from the client of the player using the item to the server. At the server level, a list of nearby players is made and each is sent a separate packet, "ParticleReceivePacket" to their client. (I know these names are not the best, my apologies.) The packets are sending perfectly fine, I have checked this by sending chat messages to players sending and receiving packets. The issue is that I can't find out how to send the original player as a variable to the clients receiving the packet. Sending specific information through a packet seems that it should be a no-brainer, that's pretty much what they're meant for as I understand. But for some reason how to do this completely escapes me. Any advice?

Here's where I register my packets:
ModMessages.class

package com.pinkdotnet.wowozela;

import com.pinkdotnet.wowozela.packet.ParticlePacket;
import com.pinkdotnet.wowozela.packet.ParticleReceivePacket;

import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;

public class ModMessages {
	private static SimpleChannel INSTANCE;
	
	private static int packetId = 0;
	private static int id() {
		return packetId++;
	}
	
	public static void register()
	{
		SimpleChannel net = NetworkRegistry.ChannelBuilder
				.named(new ResourceLocation(Wowozela.MODID, "messages"))
				.networkProtocolVersion(() -> "1.0")
				.clientAcceptedVersions(s -> true)
				.serverAcceptedVersions(s -> true)
				.simpleChannel();
		INSTANCE = net;
		
		net.messageBuilder(ParticlePacket.class, id(), NetworkDirection.PLAY_TO_SERVER)
			.decoder(ParticlePacket::new)
			.encoder(ParticlePacket::toBytes)
			.consumerMainThread(ParticlePacket::handle)
			.add();
		net.messageBuilder(ParticleReceivePacket.class, id(), NetworkDirection.PLAY_TO_CLIENT)
		.decoder(ParticleReceivePacket::new)
		.encoder(ParticleReceivePacket::toBytes)
		.consumerMainThread(ParticleReceivePacket::handle)
		.add();
	}
	
	
	
	public static <MSG> void sendToServer(MSG message) {
		INSTANCE.sendToServer(message);
	}
	
	public static <MSG> void sendToPlayer(MSG message, ServerPlayer player) {
		INSTANCE.send(PacketDistributor.PLAYER.with(()-> player), message);
	}
}

Here's my client-to-server packet, sent when an item is used:

ParticlePacket.class

package com.pinkdotnet.wowozela.packet;

import java.io.Console;
import java.util.List;
import java.util.function.Supplier;

import com.pinkdotnet.wowozela.ModMessages;
import com.pinkdotnet.wowozela.particle.ModParticles;

import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;
import net.minecraft.network.chat.Component;

public class ParticlePacket {
	public ParticlePacket() {
		
	}
	
	public ParticlePacket(FriendlyByteBuf buf) {
		
	}
	
	public void toBytes(FriendlyByteBuf buf) {
		
	}
	
	public boolean handle(Supplier<NetworkEvent.Context> supplier) {
		NetworkEvent.Context context = supplier.get();
		context.enqueueWork(() -> {
			// ON SERVER
			ServerPlayer sender = context.getSender();
			ServerLevel level = sender.getLevel();
			
			List<ServerPlayer> playersList = level.players();
			
			
			for(ServerPlayer player : playersList)
			{
				if(player != sender)
				{
					double distance = Math.sqrt(Math.pow(player.position().x - sender.position().x, 2) + Math.pow(player.position().z - sender.position().z, 2));
					if(distance < 30) {
						ModMessages.sendToPlayer(new ParticleReceivePacket(), player);
					}
				}
			}
		});
		return true;
	}
}

And here's my server-to-client packet, sent to all nearby players.
 

package com.pinkdotnet.wowozela.packet;

import java.io.Console;
import java.util.List;
import java.util.function.Supplier;

import com.pinkdotnet.wowozela.particle.ModParticles;

import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;
import net.minecraft.network.chat.Component;

public class ParticleReceivePacket {

	public ParticleReceivePacket() {

	}
	
	public ParticleReceivePacket(FriendlyByteBuf buf) {
		
	}
	
	public void toBytes(FriendlyByteBuf buf) {
		
	}
	
	public static boolean handle(ParticleReceivePacket message, Supplier<NetworkEvent.Context> supplier) {
		NetworkEvent.Context context = supplier.get();
		context.enqueueWork(() -> {
			// ON CLIENT

			//Below line will spawn particles at location of sender, when sender is avaliable
			//level.addParticle(ModParticles.WOWOZELA_PARTICLES.get(), message.sender.position().x, message.sender.position().y + 1.5, message.sender.position().z, ((message.sender.getLookAngle().x/2)), ((message.sender.getLookAngle().y/2)), ((message.sender.getLookAngle().z/2)));
			
		});
		return true;
	}
}

How can I send the sender of the first packet to the receiver of the second one? Feel free to tell me how dumb I am, because I can already feel that the answer to this one is going to be obvious, I just can't find it anywhere and can't figure it out myself.
EDIT 1: Do I need to handle the server-to-client packet in a separate class from the packet class?

Edited by mintmeal
Elaborating on the original question
Link to comment
Share on other sites

Please don't dump code snippets in the forum.

Post complete reproducable examples to github so we can see everything in context.

e.g. you don;t show your item code that triggers all this

 

You shouldn't need to do any custom networking for this unless your processing is none standard.

That item "use" method should get called on both the client and server.

 

From the server you can use ServerLevel.sendParticles()

See for example PotionItem.useOn() which calls sendParticles when isClientSide is false - there are many other examples in the vanilla code

 

https://forge.gemwire.uk/wiki/Particles#Spawning_Particles

 

To answer exact question:

Players are Entitys. Minecraft serializes them over the network using their entityId.

But the player is often implicit in the connection. Its only when another player is referenced that these ids get sent.

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

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



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Hiii. I wanted to add audio capability in MineRL (Minecraft based environment for Reinforcement Learning) which uses MCP Reborn. Any ideas in how I can capture the audio ?
    • Cryptocurrency investments can be tempting, promising respectable returns and financial freedom. However, the harsh reality is that the digital landscape is rife with scams and fraudulent schemes, leaving unsuspecting individuals vulnerable to monetary loss. I learned this lesson the hard way when I fell victim to a fraudulent cryptocurrency exchange scam, losing a significant amount of money. It was a devastating blow, one that left me feeling hopeless and lost, unsure of where to turn for help. But in my darkest hour, a beacon of hope emerged in the form of a colleague who recommended a professional team of hackers called Muyern Trust Hacker. With their specialization in money recovery, they offered a glimmer of hope in what seemed like an insurmountable situation. Upon contacting Muyern Trust Hacker, I was immediately struck by their professionalism and competence. They listened to my story with empathy and understanding, assuring me that all hope was not lost. With their guidance and expertise, I journeyed to reclaim what was rightfully mine. The process was not without its challenges, but with Muyern Trust Hacker by my side, I felt empowered and supported every step of the way. Their team of skilled hackers utilized advanced techniques and strategies to trace and recover my lost investment, delivering results that exceeded my expectations. I was impressed not only by their technical prowess but also by their unwavering commitment to their client's well-being. They provided regular updates and reassurance throughout the recovery process, instilling confidence and trust in their abilities. Thanks to Muyern Trust Hacker's extraordinary efforts, I could reclaim my lost investment and emerge from the ordeal with renewed hope and optimism. Their professionalism, integrity, and dedication to their craft were truly commendable, and I am forever grateful for their assistance during my time of need. If you or someone you know has fallen victim to online scams or fraudulent schemes, don't despair. Reach out to Muyern Trust Hacker and let them guide you toward a solution. By sharing my story, I hope to increase awareness and save others from becoming victims of these dishonest schemes. ( ht tps : //muyerntrusthack .solutions/ ) ( Mail; muyerntrusted(at) mail-me (dot)c o m ) ( SIGNAL +1 585 2-2-8 86-05 )
    • Firstly paste the report into this website: https://mclo.gs/ and then send it again afterwards.
    • REMEMBER, ITS FABRIC 1.18.2 I'm not sure why my minecraft game had crashed, when I turned into a ghost I tried to harvest soul away from a spider since it had a soul with a empty soul vessel, but it instantly made my game crash, maybe it was because of sodium or something like that? Crash report: https://mclo.gs/oHzmbyF
  • Topics

×
×
  • Create New...

Important Information

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