Pour développer une application client-serveur de sondage en Java, nous pouvons utiliser des sockets pour la communication réseau, la classe ExecutorService pour gérer le pool de threads pour les clients multiples, et des collections synchronisées pour s'assurer que les votes sont traités de manière thread-safe.
Voici une implémentation de base pour les classes Sondage, Serveur, et Client:
Classe Sondage:
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class Sondage {
private ConcurrentHashMap<String, AtomicInteger> candidats; // Thread-safe collection
public Sondage() {
candidats = new ConcurrentHashMap<>();
}
public void addCandidat(String candidat) {
candidats.put(candidat, new AtomicInteger());
}
public String getCandidats() {
return String.join(", ", candidats.keySet());
}
public String vote(int choix) {
int index = 1;
for (String key : candidats.keySet()) {
if (index == choix) {
candidats.get(key).incrementAndGet();
return "OK";
}
index++;
}
return "ERR";
}
public String getResultat() {
return candidats.entrySet().stream()
.max((entry1, entry2) -> Integer.compare(entry1.getValue().get(), entry2.getValue().get()))
.map(entry -> entry.getKey() + " with " + entry.getValue().get() + " vote(s)")
.orElse("No votes have been cast yet");
}
}
Classe Serveur:
import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Serveur {
private static final int PORT = 1234;
private ServerSocket serverSocket;
private Sondage sondage;
private ExecutorService clientHandlerPool;
public Serveur() {
try {
serverSocket = new ServerSocket(PORT);
sondage = new Sondage();
clientHandlerPool = Executors.newFixedThreadPool(10); // Pool for up to 10 clients
// Initialize candidates for simplicity
sondage.addCandidat("Candidat 1");
sondage.addCandidat("Candidat 2");
sondage.addCandidat("Candidat 3");
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
System.out.println("Server is running on port " + PORT);
while (true) {
try {
Socket clientSocket = serverSocket.accept();
clientHandlerPool.execute(new ClientHandler(clientSocket, sondage));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class ClientHandler implements Runnable {
private Socket clientSocket;
private Sondage sondage;
public ClientHandler(Socket socket, Sondage sondage) {
this.clientSocket = socket;
this.sondage = sondage;
}
@Override
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
if ("candidats".equalsIgnoreCase(inputLine)) {
out.println(sondage.getCandidats());
} else if (inputLine.startsWith("vote")) {
int choix = Integer.parseInt(inputLine.substring(5));
out.println(sondage.vote(choix));
} else if ("resultat".equalsIgnoreCase(inputLine)) {
out.println(sondage.getResultat());
} else {
out.println("ERR: Unknown command");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Classe Client:
import java.io.*;
import java.net.*;
public class Client {
private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 1234;
public static void main(String[] args) {
try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Server says: " + in.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Pour exécuter le serveur, créez d'abord une instance de Serveur et appelez la méthode start():
public class MainServer {
public static void main(String[] args) {
Serveur server = new Serveur();
server.start();
}
}
Pour le client, vous pouvez lancer plusieurs instances de Client et interagir avec le serveur en utilisant les commandes décrites (candidats, vote N, resultat).
C'est une implémentation de base pour vous aider à démarrer, et elle peut être étendue avec des fonctionnalités supplémentaires comme la validation d'entrée et la gestion des erreurs. Aussi, la sécurité, l'authentification des clients, et la scalabilité sont des aspects à prendre en compte selon les besoins spécifiques de l'application.