tweaks724/src/main/java/eu/m724/tweaks/ping/KeepAlivePingChecker.java
Minecon724 b23f773198
All checks were successful
/ deploy (push) Successful in 5m3s
New ping checker
2024-11-30 20:13:22 +01:00

69 lines
2.2 KiB
Java

/*
* Copyright (C) 2024 Minecon724
* Tweaks724 is licensed under the GNU General Public License. See the LICENSE.md file
* in the project root for the full license text.
*/
package eu.m724.tweaks.ping;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
public class KeepAlivePingChecker extends BukkitRunnable {
// ID, timestamp
private final Map<Long, Long> keepAliveIDs = new HashMap<>();
private final Plugin plugin;
KeepAlivePingChecker(Plugin plugin) {
this.plugin = plugin;
}
public void start() {
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(
plugin,
ListenerPriority.NORMAL,
PacketType.Play.Client.KEEP_ALIVE
) {
@Override
public void onPacketReceiving(PacketEvent event) {
long id = event.getPacket().getLongs().read(0);
Long start = keepAliveIDs.remove(id);
if (start != null) {
Player player = event.getPlayer();
PlayerPingStorage.submitPing(player, System.nanoTime() - start);
// server will kick if we don't cancel
event.setCancelled(true);
}
}
});
this.runTaskTimerAsynchronously(plugin, 0, 40); // 2 secs
}
@Override
public void run() {
plugin.getServer().getOnlinePlayers().forEach(player -> {
long id = ThreadLocalRandom.current().nextLong();
keepAliveIDs.put(id, System.nanoTime());
PacketContainer packet = new PacketContainer(PacketType.Play.Server.KEEP_ALIVE);
packet.getLongs().write(0, id);
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
});
}
}