jNetServer/src/main/java/jnet/server/userping/PingManager.java

73 lines
2.7 KiB
Java

package jnet.server.userping;
import io.netty.channel.Channel;
import jnet.lib.LogFile;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
public class PingManager {
// Mapa: Channel -> (pingId -> UserPing)
private static final ConcurrentHashMap<Channel, ConcurrentHashMap<String, UserPing>> pingMap = new ConcurrentHashMap<>();
/**
* Spustí nový ping pro daný kanál.
* @param channel klient
* @param ipAddress IP adresa
* @param frameName identifikátor okna (použijeme jako součást pingId)
* @param sender funkce pro odeslání odpovědi (zavolá se s řádkem výstupu)
* @return pingId unikátní identifikátor spuštěného pingu
*/
public static String startPing(Channel channel, String ipAddress, String frameName, Consumer<String> sender) {
String pingId = ipAddress + ":" + frameName;
// Získáme nebo vytvoříme vnitřní mapu pro tento kanál
ConcurrentHashMap<String, UserPing> userPings = pingMap.computeIfAbsent(channel, k -> new ConcurrentHashMap<>());
// Pokud už ping s tímto ID existuje, nejprve ho zastavíme
UserPing oldPing = userPings.remove(pingId);
if (oldPing != null) {
oldPing.stopPing();
}
UserPing newPing = new UserPing(pingId, ipAddress, sender);
userPings.put(pingId, newPing);
Thread thread = new Thread(newPing, "Ping-" + pingId + "-" + channel.id());
thread.start();
LogFile.printInfo("Ping started for " + channel.remoteAddress() + " IP: " + ipAddress + " frame: " + frameName);
return pingId;
}
/**
* Zastaví konkrétní ping podle pingId.
*/
public static void stopPing(Channel channel, String pingId) {
ConcurrentHashMap<String, UserPing> userPings = pingMap.get(channel);
if (userPings != null) {
UserPing ping = userPings.remove(pingId);
if (ping != null) {
ping.stopPing();
LogFile.printInfo("Ping stopped for " + channel.remoteAddress() + " ID: " + pingId);
}
if (userPings.isEmpty()) {
pingMap.remove(channel);
}
}
}
/**
* Zastaví všechny pingy pro daný kanál (při odpojení).
*/
public static void stopAllPings(Channel channel) {
ConcurrentHashMap<String, UserPing> userPings = pingMap.remove(channel);
if (userPings != null) {
for (UserPing ping : userPings.values()) {
ping.stopPing();
}
LogFile.printInfo("All pings stopped for " + channel.remoteAddress());
}
}
}