feat: handle client deconnexion

This commit is contained in:
Morph01
2025-04-01 12:47:54 +02:00
parent 4894c2555d
commit 5b3abadfb6
4 changed files with 99 additions and 36 deletions

View File

@@ -55,4 +55,5 @@ task runClient(type: JavaExec) {
mainClass = application.mainClass
classpath = sourceSets.main.runtimeClasspath
args = ['--client']
standardInput = System.in
}

View File

@@ -3,12 +3,20 @@ package clientserver.client;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import clientserver.server.Server;
public class Client {
InetAddress clientAddress;
int clientPort;
private InetAddress serverAddress;
private int serverPort;
private String pseudo;
public void setPort(int port) {
this.clientPort = port;
@@ -22,28 +30,85 @@ public class Client {
return this.clientAddress;
}
public InetAddress getServerAddress() {
return this.serverAddress;
}
public int getServerPort() {
return this.serverPort;
}
public String getPseudo() {
return this.pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public Client(InetAddress address, int port) {
this.clientAddress = address;
this.clientPort = port;
}
public static Client createAndConfigureClient(DatagramSocket socketClient) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your Pseudo :");
String userPseudo = scan.next();
// Créer le client avec l'adresse locale et le port du socket
Client client = new Client(socketClient.getLocalAddress(), socketClient.getLocalPort());
client.pseudo = userPseudo;
System.out.println("Enter the IP address of the server :");
try {
client.serverAddress = InetAddress.getByName(scan.next());
} catch (UnknownHostException e) {
System.err.println("The address you choose create an UnknownHostException : " + e);
}
System.out.println("Enter the port of the server :");
client.serverPort = scan.nextInt();
scan.close();
if (socketClient != null && client.serverAddress != null) {
Server.sendMessage(socketClient, client.getPseudo(), client.serverAddress, client.serverPort);
System.out.println("New connection request sent");
}
return client;
}
private static void deconnexionClient(DatagramSocket socketClient, Client client, int handlerPort) {
try {
String disconnectMsg = "DISCONNECT";
byte[] disconnectData = disconnectMsg.getBytes();
DatagramPacket disconnectPacket = new DatagramPacket(
disconnectData,
disconnectData.length,
client.getServerAddress(),
handlerPort);
socketClient.send(disconnectPacket);
System.out.println("Déconnexion envoyée au serveur sur le port " + handlerPort);
} catch (Exception e) {
System.err.println("Erreur lors de l'envoi du message de déconnexion : " + e);
}
}
public static void main(String[] args) {
try {
// 1 - Création du canal avec un port libre
DatagramSocket socketClient = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost");
int serverPort = 6666;
DatagramSocket socketClient = null;
try {
// 1 - Création du canal avec un port libre
socketClient = new DatagramSocket();
} catch (SocketException e) {
System.err.println("The client socket cannot be created : " + e);
return;
}
// 2 - Envoyer un message au serveur
String pseudo = "PseudoTest";
byte[] sendData = pseudo.getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData,
sendData.length,
serverAddress,
serverPort);
socketClient.send(sendPacket);
System.out.println("New connection request sent");
// 2 - Création du client avec l'envoi du pseudo pour l'établissement de la
// connexion avec le server
Client client = createAndConfigureClient(socketClient);
// 3 - Recevoir
byte[] receivedData = new byte[1024]; // tampon de réception
@@ -57,19 +122,19 @@ public class Client {
receivedPacket.getLength());
if (reponse.startsWith("PORT:")) {
int newPort = Integer.parseInt(reponse.substring(5));
int newClientHandlerPort = Integer.parseInt(reponse.substring(5));
System.out.println("Connected on port:" + newPort);
System.out.println("Connected on port:" + newClientHandlerPort);
// 4 - Communiquer sur le nouveau port
for (int i = 0; i < 20; i++) {
for (int i = 0; i < 3; i++) {
String messagePort = "Test";
byte[] envoyeesPort = messagePort.getBytes();
DatagramPacket paquetPort = new DatagramPacket(
envoyeesPort,
envoyeesPort.length,
serverAddress,
newPort);
client.getServerAddress(),
newClientHandlerPort);
socketClient.send(paquetPort);
System.out.println("Test sent");
@@ -96,6 +161,7 @@ public class Client {
TimeUnit.SECONDS.sleep(1);
}
deconnexionClient(socketClient, client, newClientHandlerPort);
}
// 5 - Libérer le canal

View File

@@ -15,10 +15,18 @@ public class ClientHandler implements Runnable {
this.client = client;
}
public void sendConnectedClients() {
private void sendConnectedClients() {
Server.sendMessage(clientHandlerSocket, Server.getPseudos(), client.getAddress(), client.getPort());
}
private void handleDeconnexion(String message) {
if (message.equals("DISCONNECT")) {
System.out.println("Déconnexion du client : " + client.getPseudo());
Server.removeClientHandler(client.getPseudo());
stop();
}
}
public void stop() {
running = false;
if (clientHandlerSocket != null && !clientHandlerSocket.isClosed()) {
@@ -34,12 +42,6 @@ public class ClientHandler implements Runnable {
":" +
client.getPort());
// try {
// socket.setSoTimeout(30000);
// } catch (Exception e) {
// System.err.println("Could not set socket timeout");
// }
while (running && !clientHandlerSocket.isClosed()) {
DatagramPacket packet = Server.receivedPacket(clientHandlerSocket);
if (packet == null)
@@ -58,14 +60,7 @@ public class ClientHandler implements Runnable {
message);
sendConnectedClients();
// Reply with echo
// String response = "ECHO: " + message;
// Server.sendMessage(
// socket,
// response,
// client.getAddress(),
// client.getPort()
// );
handleDeconnexion(message);
}
System.out.println(

View File

@@ -110,6 +110,7 @@ public class Server {
int clientHandlerLocalPort = clientHandlerSocket.getLocalPort();
Client client = new Client(clientAddress, originalClientPort);
client.setPseudo(pseudoMessage);
// Send new port information to client
String response = "PORT:" + clientHandlerLocalPort;
@@ -125,7 +126,7 @@ public class Server {
thread.start();
// Add client handler to mapPseudosConnectedClients
mapPseudosConnectedClientsHandlers.putIfAbsent(pseudoMessage, handler);
addConnectedClientHandler(pseudoMessage, handler);
}
public void run() {
@@ -152,7 +153,7 @@ public class Server {
mapPseudosConnectedClientsHandlers.putIfAbsent(pseudo, clientHandler);
}
public void removeClientHandler(String pseudo) {
public static void removeClientHandler(String pseudo) {
mapPseudosConnectedClientsHandlers.remove(pseudo);
}
}