How to get player's ping in spigot 1.16.4

社会主义新天地 提交于 2021-02-17 03:32:27

问题


I tried to use java reflection in many ways to get the ping of a player. But at 100%, it returns 0ms.

I've searched for a long time, so... can someone help me?

Try 1 :

    public static int getPing(Player p) {

       try {

           Object craftPlayer = (CraftPlayer) p;
           return (int) craftPlayer.getClass().getField("ping").get(craftPlayer);

       } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | 
       SecurityException e) {
           throw new Error(e);
       }

    }

Try2 :

    public static int getPing(Player p) {

       EntityPlayer player = ((CraftPlayer) p).getHandle();
       return player.ping;

    }
    

Try 3 :

    int ping = 0;
    Class<?>[] parameterTypes = null;
        
    Class<CraftPlayer> metadata = CraftPlayer.class;
    Method[] methods = metadata.getDeclaredMethods();
    for(Method method : methods) {  
        if(method.getName().equalsIgnoreCase("getHandle")) {
            parameterTypes = method.getParameterTypes();
        }
    }
        
    try {

        Object entityPlayer = p.getClass().getDeclaredMethod("getHandle", 
        parameterTypes).invoke((CraftPlayer) p);
        ping = (int) entityPlayer.getClass().getDeclaredField("ping").get(entityPlayer);

    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                | NoSuchMethodException | SecurityException | NoSuchFieldException e) {
            e.printStackTrace();
        }

Try 4 :

        int ping = 0;
        
        try {

            Object entityPlayer = p.getClass().getMethod("getHandle").invoke(p);
            ping = entityPlayer.getClass().getField("ping").getInt(entityPlayer);

        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | 
        SecurityException e) {
            e.printStackTrace();
        }

And 3 more... (Similar to this or definitively not good for usage)

I'm testing my plugin on a VPS-Hosted 1.16.4 PaperMC server.

Maybe it will be different on a dedicated machine.

I tried to use "compact" code like this :

int ping = ((CraftPlayer) p).getHandle().ping;

... but it returns 0ms again.

Please note that I'm a real Java novice. I'm practicing to improve my level.

I'm not searching the final solution, but just an answer if my aproach is OK. If not, a good way to do this.


回答1:


Finally, it works.

The problem is my FAI : A few days ago, I opened 25565 ports for UDP/TCP and I also change other parameters.

Since I turn off all these options, my ping was magically back to 8-12 ms.

Thanks kahveci for your edit suggestion and sorry for the inconvenience.



来源:https://stackoverflow.com/questions/64988636/how-to-get-players-ping-in-spigot-1-16-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!