Jump to content

How to Disconnect Player When is SinglePlayer


jredfox

Recommended Posts

Why?: I need EntityUtil.dissconnectPlayer(player) to always  work:

I wrote up a command to disconnect the player and it just freezes the game and doesn't go to the main menu.

package com.EvilNotch.lib.minecraft.content.commands;

import com.EvilNotch.lib.minecraft.EntityUtil;

import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.TextComponentString;

public class CMDKick extends CommandBase {
	
	 /**
     * Gets the name of the command
     */
	@Override
    public String getName()
    {
        return "bootPlayer";
    }
    /**
    * Gets the usage string for the command.
    */
    @Override
    public String getUsage(ICommandSender sender)
    {
       return "commands.evilnotchlib.boot.usage";
    }
	@Override
	public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException 
	{
		Entity e = getEntity(server, sender, args[0]);	
		if(e instanceof EntityPlayerMP)
		{
			EntityPlayerMP player = (EntityPlayerMP)e;
			player.connection.disconnect(new TextComponentString("booted"));
		}
	}

    /**
     * Get a list of options for when the user presses the TAB key
     */
    @Override
    public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
    {
        return args.length != 1 ? Collections.emptyList() : getListOfStringsMatchingLastWord(args, server.getOnlinePlayerNames());
    }

}

 

Edited by jredfox
Link to comment
Share on other sites

It mostly looks like it should work, although I'm not exactly sure why you're using getEntity(). I think there is a getPlayer() method, and also if you look at the ban command they do an different method where they look up a player name in the server's player's list.

 

I guess it is possible that in single-player the disconnect isn't really functional although I couldn't find any obvious code reason why not. Note that the disconnect() method does kick off a scheduled runnable, so your freeze is probably somehow related to that. Is there any error in the log?

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

20 minutes ago, jabelar said:

It mostly looks like it should work, although I'm not exactly sure why you're using getEntity(). I think there is a getPlayer() method, and also if you look at the ban command they do an different method where they look up a player name in the server's player's list.

 

I guess it is possible that in single-player the disconnect isn't really functional although I couldn't find any obvious code reason why not. Note that the disconnect() method does kick off a scheduled runnable, so your freeze is probably somehow related to that. Is there any error in the log?

yeah log says player logged out disconnected for reason doesn't display says saving worlds and then just stops working. Could there be a more proper way to disconnect aka stop the world and go back to the main menu if player is owner?

To clarify the screen of displaying freezes in game showing the world still but, the log shows otherwise

I have verified even adding a tick delay it still occurs occasionally. What does forge use to kick the player when it says hey don't go in this world but, then again your player doesn't even try to render it yet. Should I try and open a gui before starting the process and if so what gui? 

Edited by jredfox
Link to comment
Share on other sites

Oh yeah it looks like you need to bring up the main menu gui.

 

If you look at the code for the GuiIngameMenu class, you'll see that button 1 is the quit game (return to main menu) and the code for the action performed for that button is as follows:

 

                boolean flag = this.mc.isIntegratedServerRunning();
                boolean flag1 = this.mc.isConnectedToRealms();
                button.enabled = false;
                this.mc.world.sendQuittingDisconnectingPacket();
                this.mc.loadWorld((WorldClient)null);

                if (flag)
                {
                    this.mc.displayGuiScreen(new GuiMainMenu());
                }
                else if (flag1)
                {
                    RealmsBridge realmsbridge = new RealmsBridge();
                    realmsbridge.switchToRealms(new GuiMainMenu());
                }
                else
                {
                    this.mc.displayGuiScreen(new GuiMultiplayer(new GuiMainMenu()));
                }

 

I guess technically you should probably copy all of that code (except for the part of the button enable going to false) for the single player case. Note that since this contains reference to the Minecraft and gui classes which are client-side only, you need to put the code in your client proxy (with a dummy version in your common/server proxy) and then call the proxy method from the command class.

Edited by jabelar

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

9 hours ago, jabelar said:

Oh yeah it looks like you need to bring up the main menu gui.

 

If you look at the code for the GuiIngameMenu class, you'll see that button 1 is the quit game (return to main menu) and the code for the action performed for that button is as follows:

 


                boolean flag = this.mc.isIntegratedServerRunning();
                boolean flag1 = this.mc.isConnectedToRealms();
                button.enabled = false;
                this.mc.world.sendQuittingDisconnectingPacket();
                this.mc.loadWorld((WorldClient)null);

                if (flag)
                {
                    this.mc.displayGuiScreen(new GuiMainMenu());
                }
                else if (flag1)
                {
                    RealmsBridge realmsbridge = new RealmsBridge();
                    realmsbridge.switchToRealms(new GuiMainMenu());
                }
                else
                {
                    this.mc.displayGuiScreen(new GuiMultiplayer(new GuiMainMenu()));
                }

 

I guess technically you should probably copy all of that code (except for the part of the button enable going to false) for the single player case. Note that since this contains reference to the Minecraft and gui classes which are client-side only, you need to put the code in your client proxy (with a dummy version in your common/server proxy) and then call the proxy method from the command class.

does that get called on client or server side and should I also be disconnecting the server side and before or after? Commands run on server so what wait next tick then disconnect player?

Edited by jredfox
Link to comment
Share on other sites

Game Crash when player is owner:
https://pastebin.com/WvngUH2E

 

public static void disconnectPlayer(EntityPlayerMP player,TextComponentString msg) 
{	
	if(isPlayerOwner(player))
	{
			Minecraft mc = Minecraft.getMinecraft();
            boolean flag = mc.isIntegratedServerRunning();
            boolean flag1 = mc.isConnectedToRealms();
            mc.world.sendQuittingDisconnectingPacket();
            mc.loadWorld((WorldClient)null);

            if (flag)
            {
                mc.displayGuiScreen(new GuiMainMenu());
            }
            else if (flag1)
            {
                RealmsBridge realmsbridge = new RealmsBridge();
                realmsbridge.switchToRealms(new GuiMainMenu());
            }
            else
            {
                mc.displayGuiScreen(new GuiMultiplayer(new GuiMainMenu()));
            }
	}
	else
	{
		player.connection.disconnect(msg);
	}
}

 

Edited by jredfox
Link to comment
Share on other sites

16 minutes ago, jredfox said:

does that get called on client or server side and should I also be disconnecting the server side and before or after? Commands run on server so what wait next tick then disconnect player?

Right so what you command needs to do is see if it is on a dedicated server or integrated server. If on integrated server, it will need to send a dedicated custom packet to client. The client message receiver would run the code mentioned above.

 

i think the error message you posted is because it looks like this is running inside of a server tick handler, and a server wouldn't have the ability to create a GUI. You need custom packet to client to let it know what is going on.

 

There may be easier way to disconnect a single player, but I'm just thinking that the code above is the actual way the Minecraft already disconnects a single player so should be safe and accurate if run from the client side.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

5 minutes ago, jabelar said:

Right so what you command needs to do is see if it is on a dedicated server or integrated server. If on integrated server, it will need to send a dedicated custom packet to client. The client message receiver would run the code mentioned above.

 

i think the error message you posted is because it looks like this is running inside of a server tick handler, and a server wouldn't have the ability to create a GUI. You need custom packet to client to let it know what is going on.

 

There may be easier way to disconnect a single player, but I'm just thinking that the code above is the actual way the Minecraft already disconnects a single player so should be safe and accurate if run from the client side.

I shouldn't need packets since I am the server and client. let my try that code from the client side

Link to comment
Share on other sites

23 minutes ago, jabelar said:

 

I tried running the thing that's always suppose to work but, sometimes it freezes the game. player.connection.disconnect(msg); on server side. And it always froze from the command.

Edited by jredfox
Link to comment
Share on other sites

29 minutes ago, jredfox said:

I shouldn't need packets since I am the server and client. 

Wrong. You really, really need to understand the client and server stuff. When there is integrated server ("single player") there is still a separate client and server thread and they still communicate using packets. The packets just use the link local address (127.0.0.1 I think) but they are still being used!

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

7 minutes ago, jabelar said:

Wrong. You really, really need to understand the client and server stuff. When there is integrated server ("single player") there is still a separate client and server thread and they still communicate using packets. The packets just use the link local address (127.0.0.1 I think) but they are still being used!

ok

Edited by jredfox
Link to comment
Share on other sites

4 minutes ago, jabelar said:

Wrong. You really, really need to understand the client and server stuff. When there is integrated server ("single player") there is still a separate client and server thread and they still communicate using packets. The packets just use the link local address (127.0.0.1 I think) but they are still being used!

wait just realize my idea can't work since I want it to be a server utility how to disconnect player from server side only?

Link to comment
Share on other sites

7 minutes ago, jredfox said:

wait just realize my idea can't work since I want it to be a server utility how to disconnect player from server side only?

Okay. In that case the closest thing I can think of is the ban command. You can look at that code. However, your original code seemed to be close to that so I'm not totally sure why it didn't work. It is possible that you were calling the server side disconnect method from the client and so that might have caused your original problem.

 

In the ban player command, they use this code:

                EntityPlayerMP entityplayermp = server.getPlayerList().getPlayerByUsername(args[0]);

                if (entityplayermp != null)
                {
                    entityplayermp.connection.disconnect(new TextComponentTranslation("multiplayer.disconnect.banned", new Object[0]));
                }

 

Where obviously your command usage would need the player name as args[0].

 

But this is very close to your original code, so not quite sure what the difference is except it uses different way to get the player instance.

Edited by jabelar

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Link to comment
Share on other sites

10 minutes ago, diesieben07 said:

Look at the kick command.

it's not usable on client side till 1.13 and I can't view the code. maybe they have a custom new packet or fixed something?

how do I view the source for that command?

Edited by jredfox
Link to comment
Share on other sites

3 minutes ago, jabelar said:

Okay. In that case the closest thing I can think of is the ban command. You can look at that code. However, your original code seemed to be close to that so I'm not totally sure why it didn't work. It is possible that you were calling the server side disconnect method from the client and so that might have caused your original problem.

 

In the ban player command, they use this code:


                EntityPlayerMP entityplayermp = server.getPlayerList().getPlayerByUsername(args[0]);

                if (entityplayermp != null)
                {
                    entityplayermp.connection.disconnect(new TextComponentTranslation("multiplayer.disconnect.banned", new Object[0]));
                }

 

Where obviously your command usage would need the player name as args[0].

player connection disconnect is what I was using I could try make a new object that is null at first index like yours but, that is the only difference besides you forcing full player names difficult to type when in mdk.

Link to comment
Share on other sites

14 minutes ago, jabelar said:

Okay. In that case the closest thing I can think of is the ban command. You can look at that code. However, your original code seemed to be close to that so I'm not totally sure why it didn't work. It is possible that you were calling the server side disconnect method from the client and so that might have caused your original problem.

 

In the ban player command, they use this code:


                EntityPlayerMP entityplayermp = server.getPlayerList().getPlayerByUsername(args[0]);

                if (entityplayermp != null)
                {
                    entityplayermp.connection.disconnect(new TextComponentTranslation("multiplayer.disconnect.banned", new Object[0]));
                }

 

Where obviously your command usage would need the player name as args[0].

 

But this is very close to your original code, so not quite sure what the difference is except it uses different way to get the player instance.

woah that seemed to fix it changing it from TextComponentString > TextComponentTranslation made all the difference thank you so much here is my server only 100% kick command 1.13 equivalent in 1.12.2
 

	public static void disconnectPlayer(EntityPlayerMP player,TextComponentString msg) 
	{	
		player.connection.disconnect(new TextComponentTranslation(msg.getText(),new Object[0]) );
	}

 

Link to comment
Share on other sites

14 minutes ago, diesieben07 said:

What are you even saying...

	public static void disconnectPlayer(EntityPlayerMP player,TextComponentString msg) 
	{	
		player.connection.disconnect(new TextComponentTranslation(msg.getText(),new Object[0]) );
	}

Command seems to freeze the game if something else is loading why is it occurring?

Link to comment
Share on other sites

35 minutes ago, jabelar said:

Okay. In that case the closest thing I can think of is the ban command. You can look at that code. However, your original code seemed to be close to that so I'm not totally sure why it didn't work. It is possible that you were calling the server side disconnect method from the client and so that might have caused your original problem.

 

In the ban player command, they use this code:


                EntityPlayerMP entityplayermp = server.getPlayerList().getPlayerByUsername(args[0]);

                if (entityplayermp != null)
                {
                    entityplayermp.connection.disconnect(new TextComponentTranslation("multiplayer.disconnect.banned", new Object[0]));
                }

 

Where obviously your command usage would need the player name as args[0].

 

But this is very close to your original code, so not quite sure what the difference is except it uses different way to get the player instance.

so it's not always working if the world is loading not giving it absolute non loading the game will freeze with booting the player. Should I be pausing the game if player is owner?

Edited by jredfox
Link to comment
Share on other sites

13 minutes ago, diesieben07 said:

What do you mean by "something else is loading"? Why are you putting the text of a TextComponentString into a TextComponentTranslation? Where are you calling this method?

I am calling the method disconnectPlayer() from the command class.

Since the client has to have the mod anyways to use the command and have the issue having client only code is acceptable and if is on server only I know it's always going to work with player disconnect

Edited by jredfox
Link to comment
Share on other sites

13 minutes ago, diesieben07 said:

Check if the player is the server owner (MinecraftServer::isSinglePlayer && MinecraftServer::getServerOwner().equals(player.getName())), if so, shut down the server instead of kicking (MinecraftServer::initiateShutdown) or show an error message, etc.

player.mcServer.initiateShutdown() > doesn't allow for a custom message any ideas?

Edited by jredfox
Link to comment
Share on other sites

7 minutes ago, diesieben07 said:

Custom implementation. Look at GuiIngameMenu::actionPerformed case 1 ("quit game" handler).

It executes off of the client side code I would have to do adjustments.

Since this is guaranteed to work though I was thinking since I am the client just override the gui open event when necessary and display my gui disconnected. Might not be proper but, gui screens pause the game and my command does not

Edited by jredfox
Link to comment
Share on other sites

48 minutes ago, diesieben07 said:

Yep, that's what you gotta do.

well I don't think the player logout event is getting fired when I called server shutdown? are you sure that's the right code or should I be using what jeblar sent me?

Link to comment
Share on other sites

1 minute ago, diesieben07 said:

Well, of course it's not fired. The player is not logging out, the server is closing. The event should not be fired here.

so how to do this properly then?

Edited by jredfox
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

    • I have done this now but have got the error:   'food(net.minecraft.world.food.FoodProperties)' in 'net.minecraft.world.item.Item.Properties' cannot be applied to                '(net.minecraftforge.registries.RegistryObject<net.minecraft.world.item.Item>)' public static final RegistryObject<Item> LEMON_JUICE = ITEMS.register( "lemon_juice", () -> new Item( new HoneyBottleItem.Properties().stacksTo(1).food( (new FoodProperties.Builder()) .nutrition(3) .saturationMod(0.25F) .effect(() -> new MobEffectInstance(MobEffects.DAMAGE_RESISTANCE, 1500), 0.01f ) .build() ) )); The code above is from the ModFoods class, the one below from the ModItems class. public static final RegistryObject<Item> LEMON_JUICE = ITEMS.register("lemon_juice", () -> new Item(new Item.Properties().food(ModFoods.LEMON_JUICE)));   I shall keep going between them to try and figure out the cause. I am sorry if this is too much for you to help with, though I thank you greatly for your patience and all the effort you have put in to help me.
    • I have been following these exact tutorials for quite a while, I must agree that they are amazing and easy to follow. I have registered the item in the ModFoods class, I tried to do it in ModItems (Where all the items should be registered) but got errors, I think I may need to revert this and figure it out from there. Once again, thank you for your help! 👍 Just looking back, I have noticed in your code you added ITEMS.register, which I am guessing means that they are being registered in ModFoods, I shall go through the process of trial and error to figure this out.
    • ♈+2349027025197ஜ Are you a pastor, business man or woman, politician, civil engineer, civil servant, security officer, entrepreneur, Job seeker, poor or rich Seeking how to join a brotherhood for protection and wealth here’s is your opportunity, but you should know there’s no ritual without repercussions but with the right guidance and support from this great temple your destiny is certain to be changed for the better and equally protected depending if you’re destined for greatness Call now for enquiry +2349027025197☎+2349027025197₩™ I want to join ILLUMINATI occult without human sacrificeGREATORLDRADO BROTHERHOOD OCCULT , Is The Club of the Riches and Famous; is the world oldest and largest fraternity made up of 3 Millions Members. We are one Family under one father who is the Supreme Being. In Greatorldrado BROTHERHOOD we believe that we were born in paradise and no member should struggle in this world. Hence all our new members are given Money Rewards once they join in order to upgrade their lifestyle.; interested viewers should contact us; on. +2349027025197 ۝ஐℰ+2349027025197 ₩Greatorldrado BROTHERHOOD OCCULT IS A SACRED FRATERNITY WITH A GRAND LODGE TEMPLE SITUATED IN G.R.A PHASE 1 PORT HARCOURT NIGERIA, OUR NUMBER ONE OBLIGATION IS TO MAKE EVERY INITIATE MEMBER HERE RICH AND FAMOUS IN OTHER RISE THE POWERS OF GUARDIANS OF AGE+. +2349027025197   SEARCHING ON HOW TO JOIN THE Greatorldrado BROTHERHOOD MONEY RITUAL OCCULT IS NOT THE PROBLEM BUT MAKE SURE YOU'VE THOUGHT ABOUT IT VERY WELL BEFORE REACHING US HERE BECAUSE NOT EVERYONE HAS THE HEART TO DO WHAT IT TAKES TO BECOME ONE OF US HERE, BUT IF YOU THINK YOU'RE SERIOUS MINDED AND READY TO RUN THE SPIRITUAL RACE OF LIFE IN OTHER TO ACQUIRE ALL YOU NEED HERE ON EARTH CONTACT SPIRITUAL GRANDMASTER NOW FOR INQUIRY +2349027025197   +2349027025197 Are you a pastor, business man or woman, politician, civil engineer, civil servant, security officer, entrepreneur, Job seeker, poor or rich Seeking how to join
    • Hi, I'm trying to use datagen to create json files in my own mod. This is my ModRecipeProvider class. public class ModRecipeProvider extends RecipeProvider implements IConditionBuilder { public ModRecipeProvider(PackOutput pOutput) { super(pOutput); } @Override protected void buildRecipes(Consumer<FinishedRecipe> pWriter) { ShapedRecipeBuilder.shaped(RecipeCategory.MISC, ModBlocks.COMPRESSED_DIAMOND_BLOCK.get()) .pattern("SSS") .pattern("SSS") .pattern("SSS") .define('S', ModItems.COMPRESSED_DIAMOND.get()) .unlockedBy(getHasName(ModItems.COMPRESSED_DIAMOND.get()), has(ModItems.COMPRESSED_DIAMOND.get())) .save(pWriter); ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, ModItems.COMPRESSED_DIAMOND.get(),9) .requires(ModBlocks.COMPRESSED_DIAMOND_BLOCK.get()) .unlockedBy(getHasName(ModBlocks.COMPRESSED_DIAMOND_BLOCK.get()), has(ModBlocks.COMPRESSED_DIAMOND_BLOCK.get())) .save(pWriter); ShapedRecipeBuilder.shaped(RecipeCategory.MISC, ModItems.COMPRESSED_DIAMOND.get()) .pattern("SSS") .pattern("SSS") .pattern("SSS") .define('S', Blocks.DIAMOND_BLOCK) .unlockedBy(getHasName(ModItems.COMPRESSED_DIAMOND.get()), has(ModItems.COMPRESSED_DIAMOND.get())) .save(pWriter); } } When I try to run the runData client, it shows an error:  Caused by: java.lang.IllegalStateException: Duplicate recipe compressed:compressed_diamond I know that it's caused by the fact that there are two recipes for the ModItems.COMPRESSED_DIAMOND. But I need both of these recipes, because I need a way to craft ModItems.COMPRESSED_DIAMOND_BLOCK and restore 9 diamond blocks from ModItems.COMPRESSED_DIAMOND. Is there a way to solve this?
  • Topics

×
×
  • Create New...

Important Information

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