Hi all, lately I've started developing mods that are server-side only, so I've already started working with packets, I thought it was a pretty simple thing (having already worked on it when developing plugins) (I know it's completely different at code level, but logical I think it's the same) but I ran into multiple problems, I'm developing a mod in 1.19.2 server side which for now has to send a simple message to individual clients by executing a command, like a sort of "hello world" debugging. I developed the command part and it works, but I really have no idea how to send a chatmessagepacket to the client, could someone help me?
Test.java -- Command Class (Working)
public class Test {
public Test (CommandDispatcher<CommandSourceStack> dispatcher){
dispatcher.register(Commands.literal("test").executes((command) -> {
return 0;
}));
}
private int prova(CommandSourceStack source) throws CommandSyntaxException{
ServerPlayer player = source.getPlayer();
BlockPos pos = player.blockPosition();
//here must send a packet to the client
return 1;
}
}
PacketHandler.java
public class PacketHandler {
private static SimpleChannel INSTANCE;
private static int packetId = 0;
public static void register(){
SimpleChannel net = NetworkRegistry.ChannelBuilder
.named(new ResourceLocation(Mceconomy.MODID, "main"))
.networkProtocolVersion(() -> "1.0")
.clientAcceptedVersions(s -> true)
.serverAcceptedVersions(s -> true)
.simpleChannel();
INSTANCE = net;
net.messageBuilder(MessagePacket.class, id(), NetworkDirection.PLAY_TO_SERVER)
.encoder(MessagePacket::toBytes)
.decoder(MessagePacket::new)
.consumerMainThread(MessagePacket::handle)
.add();
}
private static int id() {
return packetId++;
}
public static <MSG> void sendToServer(MSG message) {
INSTANCE.sendToServer(message);
}
public static <MSG> void sendToClient(MSG message, ServerPlayer player) {
INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), message);
}
}
MessagePacket.java -- (StringTextComponent can't find it and I don't know why)
public class MessagePacket {
public MessagePacket() {
}
public MessagePacket(FriendlyByteBuf buf) {
}
public void toBytes(FriendlyByteBuf buf) {
}
public boolean handle(Supplier<NetworkEvent.Context> supplier) {
NetworkEvent.Context context = supplier.get();
context.enqueueWork(() -> {
//On the server
ServerPlayer player = context.getSender();
ServerLevel world = player.getLevel();
player.sendSystemMessage(new StringTextComponent("Hello World!"));
});
return true;
}
}
Any ideas?