Jump to content

How to send data from client to server and handle it


MrFunny

Recommended Posts

1 minute ago, diesieben07 said:

Im currently using this, but nothing happens

package me.mrfunny.nextlevelauth;

import com.google.gson.Gson;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

// The value here should match an entry in the META-INF/mods.toml file
@Mod("nextlevelauth")
public class ExampleMod {
    // Directly reference a log4j logger.
    private static final Logger LOGGER = LogManager.getLogger();
    private static final String PROTOCOL_VERSION = "1";
    public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(
            new ResourceLocation("nextlevelauth", "authmain"),
            () -> PROTOCOL_VERSION,
            PROTOCOL_VERSION::equals,
            PROTOCOL_VERSION::equals
    );
    private int id = 0;
    public ExampleMod() {
        MinecraftForge.EVENT_BUS.register(ExampleMod.class);
        try{
            INSTANCE.registerMessage(id, AuthMessage.class, new BiConsumer<AuthMessage, PacketBuffer>() {
                @Override
                public void accept(AuthMessage authMessage, PacketBuffer packetBuffer) {
                    id++;
                    packetBuffer.writeString(authMessage.token);
                }
            }, new Function<PacketBuffer, AuthMessage>() {
                @Override
                public AuthMessage apply(PacketBuffer packetBuffer) {
                    LOGGER.info("logged in1");
                    return new AuthMessage(packetBuffer.readString());
                }
            }, new BiConsumer<AuthMessage, Supplier<NetworkEvent.Context>>() {
                @Override
                public void accept(AuthMessage authMessage, Supplier<NetworkEvent.Context> contextSupplier) {
                    LOGGER.info("logged in2");
                    handle(authMessage, contextSupplier);
                }
            });
        } catch (Exception exception){
            exception.printStackTrace();
        }

    }

    public static void handle(AuthMessage msg, Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            ServerPlayerEntity sender = ctx.get().getSender(); // the client that sent this packet
            try{
                URL url = new URL("https://nextlevel.su/api/v1/user/");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.addRequestProperty("User-Agent", "PostmanRuntime/7.26.8");
                connection.addRequestProperty("Authorization", "Bearer " + msg.token);
                connection.addRequestProperty("Content-Type", "application/json");
                connection.addRequestProperty("Accept", "application/json");
                connection.connect();
                int responseCode = connection.getResponseCode();
                if(responseCode != 200){
                    connection.disconnect();
                    sender.disconnect();
                    return;
                }
                ctx.get().setPacketHandled(true);
                connection.disconnect();
            } catch (Exception exception){
                exception.printStackTrace();
                ctx.get().getSender().disconnect();
            }
        });
    }
    @OnlyIn(Dist.CLIENT)
    @SubscribeEvent
    public static void onJoin(PlayerEvent.PlayerLoggedInEvent event){
        try {
            LOGGER.info("connected");
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    public static String readFile(String path, Charset encoding) {
        byte[] encoded = new byte[0];
        try {
            encoded = Files.readAllBytes(Paths.get(path));
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        return new String(encoded, encoding).replace("\n", "").replace("\r", "");
    }
}

My AuthMessage class
 

package me.mrfunny.nextlevelauth;

public class AuthMessage {
    public String token;
    public AuthMessage(String token){
        this.token = token;
    }
}

 

Link to comment
Share on other sites

Just now, diesieben07 said:

No, you don't.

Make a whitelist. Tada, problem solved.

I need to install mods and other things in 1 click with site and others features for server. Can you just leave example for send and handle or not?

Link to comment
Share on other sites

Just now, diesieben07 said:

No.

Custom launchers are not supported. Use an installer approach to create a profile in the vanilla launcher.

How about forge hacks and another. For example launcher checks hash, automatical update from server and another things.

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

    • Add crash-reports with sites like https://paste.ee/ Maybe an issue with blur, essentials or cumulus_menus
    • Add the crash-report or latest.log (logs-folder) with sites like https://paste.ee/ and paste the link to it here  
    • I have a problem, I am trying to put two different effects to two different armors but when I run it only the emerald armor effect works. This is the code public class ModArmorItem extends ArmorItem{ private static final Map<ArmorMaterial, MobEffectInstance> MATERIAL_TO_EFFECT_MAP = (new ImmutableMap.Builder<ArmorMaterial, MobEffectInstance>()) .put(ModArmorMaterials.EMERALD, new MobEffectInstance(MobEffects.HERO_OF_THE_VILLAGE,200, 1,false,false, true)) .put(ModArmorMaterials.OBSIDIAN, new MobEffectInstance(MobEffects.FIRE_RESISTANCE,200, 1,false,false, true)).build(); public ModArmorItem(ArmorMaterial pMaterial, Type pType, Properties pProperties) { super(pMaterial, pType, pProperties); } @Override public void onArmorTick(ItemStack stack, Level world, Player player){ if (!world.isClientSide()) { if (hasFullSuitOfArmorOn(player)) { evaluateArmorEffects(player); } } } private void evaluateArmorEffects(Player player) { for (Map.Entry<ArmorMaterial,MobEffectInstance> entry : MATERIAL_TO_EFFECT_MAP.entrySet()){ ArmorMaterial mapArmorMaterial = entry.getKey(); MobEffectInstance mapStatusEffect = entry.getValue(); if (hasCorrectArmorOn(mapArmorMaterial, player)) { addStatusEffectForMaterial(player, mapArmorMaterial, mapStatusEffect); } } } private void addStatusEffectForMaterial(Player player, ArmorMaterial mapArmorMaterial, MobEffectInstance mapStatusEffect) { boolean hasPlayerEffect = player.hasEffect(mapStatusEffect.getEffect()); if (hasCorrectArmorOn(mapArmorMaterial, player) && !hasPlayerEffect) { player.addEffect(new MobEffectInstance(mapStatusEffect)); } } private boolean hasCorrectArmorOn(ArmorMaterial material, Player player) { for (ItemStack armorStack : player.getInventory().armor){ if (!(armorStack.getItem() instanceof ArmorItem)) { return false; } } ArmorItem helmet = ((ArmorItem)player.getInventory().getArmor(3).getItem()); ArmorItem breastplace = ((ArmorItem)player.getInventory().getArmor(2).getItem()); ArmorItem leggins = ((ArmorItem)player.getInventory().getArmor(1).getItem()); ArmorItem boots = ((ArmorItem)player.getInventory().getArmor(0).getItem()); return helmet.getMaterial() == material && breastplace.getMaterial() == material && leggins.getMaterial() == material && boots.getMaterial() == material; } private boolean hasFullSuitOfArmorOn(Player player){ ItemStack helmet = player.getInventory().getArmor(3); ItemStack breastplace = player.getInventory().getArmor(2); ItemStack leggins = player.getInventory().getArmor(1); ItemStack boots = player.getInventory().getArmor(0); return !helmet.isEmpty() && !breastplace.isEmpty() && !leggins.isEmpty() && !boots.isEmpty(); } } Also when I place two effects on the same armor, the game crashes. Here is the crash file. The code is the same, only this part is different   private static final Map<ArmorMaterial, MobEffectInstance> MATERIAL_TO_EFFECT_MAP = (new ImmutableMap.Builder<ArmorMaterial, MobEffectInstance>()) .put(ModArmorMaterials.EMERALD, new MobEffectInstance(MobEffects.HERO_OF_THE_VILLAGE,200, 1,false,false, true)) .put(ModArmorMaterials.EMERALD, new MobEffectInstance(MobEffects.FIRE_RESISTANCE,200, 1,false,false, true)).build(); I hope you guys can help me. Thanks.
  • Topics

×
×
  • Create New...

Important Information

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