如何在spigot1.16.4中获得玩家的ping

xiozqbni  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(384)

我尝试了很多方法使用java反射来获得玩家的ping。但在100%时,它返回0ms。
我找了很久了,所以。。。有人能帮我吗?
尝试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;

    }

尝试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();
        }

尝试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();
        }

还有3个(与此类似或不适合使用)
我正在vps托管的1.16.4PC服务器上测试我的插件。
也许在专用机器上会有所不同。
我试着用这样的“紧凑”代码:

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

... 但它又返回0毫秒。
请注意,我是一个真正的java新手。我在练习提高我的水平。
我不是在寻找最终的解决方案,只是一个答案,如果我的方案是好的。如果不是,一个很好的方法。

mqxuamgl

mqxuamgl1#

最后,它成功了。
问题是我的fai:几天前,我为udp/tcp打开了25565个端口,我还更改了其他参数。
由于我关闭了所有这些选项,我的ping神奇地回到了8-12毫秒。
感谢kahveci的编辑建议,并对由此带来的不便表示歉意。

相关问题