From 4b8adef72f5607a607fdfc9e0dcdc4b93f5329a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment?= Date: Sun, 2 Mar 2025 13:07:09 +0100 Subject: [PATCH] fix to prevent server chat from displaying the handshakes spam --- ChatApp/src/server/Server.java | 20 ++++++++++++++++++++ ChatApp/src/server/ServerConnexion.java | 6 +++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/ChatApp/src/server/Server.java b/ChatApp/src/server/Server.java index bb0544e..125365d 100644 --- a/ChatApp/src/server/Server.java +++ b/ChatApp/src/server/Server.java @@ -18,12 +18,14 @@ public class Server implements PacketHandler { private final DatagramSocket serverSocket; private final Map connexions; + private final Map connexionTimes; private final SocketReader reader; private final Map> rooms; public Server(int port) throws SocketException { this.serverSocket = new DatagramSocket(port); this.connexions = new HashMap<>(); + this.connexionTimes = new HashMap<>(); this.reader = new SocketReader(serverSocket, this); this.rooms = new HashMap<>(); } @@ -126,4 +128,22 @@ public class Server implements PacketHandler { this.connexions.get(address).visit(packet); } + /** + * Avoid the server to spam the chat + * @param address the address of the connexion + * @return true if the connexion is the first received or older than 5 seconds + */ + public boolean handleConnexionTime(InetSocketAddress address) { + if (!connexionTimes.containsKey(address)) { + connexionTimes.put(address, Instant.now()); + return true; + } + Instant lastConnexion = connexionTimes.get(address); + if (Instant.now().isAfter(lastConnexion.plusSeconds(5))) { + connexionTimes.put(address, Instant.now()); + return true; + } + return false; + } + } diff --git a/ChatApp/src/server/ServerConnexion.java b/ChatApp/src/server/ServerConnexion.java index 03c3a04..1f7d818 100644 --- a/ChatApp/src/server/ServerConnexion.java +++ b/ChatApp/src/server/ServerConnexion.java @@ -4,6 +4,8 @@ import java.io.IOException; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.time.Instant; +import java.util.HashMap; +import java.util.Map; import network.SocketWriter; import network.protocol.Packet; @@ -96,7 +98,9 @@ public class ServerConnexion implements PacketVisitor { @Override public void visitPacket(HandshakePacket packet) { - System.out.println("[Server] Handshake received from " + clientAddress); + if(this.server.handleConnexionTime(this.clientAddress)) { + System.out.println("[Server] Handshake received from " + clientAddress); + } sendPacket(packet); }