Repository zur Vorlesung Prog3A
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DistributedSorterServer.java 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.io.PrintWriter;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. import java.util.Arrays;
  7. public class DistributedSorterServer implements Runnable {
  8. private final Socket clientSocket;
  9. // Konstruktor
  10. public DistributedSorterServer(Socket clientSocket) {
  11. this.clientSocket = clientSocket;
  12. }
  13. public static void main(String[] args) {
  14. final int port = 12345;
  15. try (ServerSocket serverSocket = new ServerSocket(port)) {
  16. System.out.println("Distributed Sorter Server is running on port " + port);
  17. while (true) {
  18. // Warten auf neue Verbindung
  19. Socket client = serverSocket.accept();
  20. System.out.println("New client connected: " + client.getInetAddress());
  21. // Neuen Thread starten, um die Client-Anfrage zu bearbeiten
  22. Thread thread = new Thread(new DistributedSorterServer(client));
  23. thread.start();
  24. }
  25. } catch (Exception e) {
  26. System.err.println("Error: " + e.getMessage());
  27. }
  28. }
  29. @Override
  30. public void run() {
  31. try (
  32. BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  33. PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)
  34. ) {
  35. String inputLine;
  36. // Verarbeite alle Nachrichten vom Client
  37. while ((inputLine = in.readLine()) != null) {
  38. System.out.println("Received: " + inputLine);
  39. // Sortiere die Buchstaben im String
  40. String sortedLine = sortCharacters(inputLine);
  41. System.out.println(inputLine + " -> " + sortedLine);
  42. // Antwort zurück an den Client senden
  43. out.println(sortedLine);
  44. }
  45. } catch (Exception e) {
  46. System.err.println("Error handling client: " + e.getMessage());
  47. } finally {
  48. try {
  49. clientSocket.close();
  50. System.out.println("Client disconnected.");
  51. } catch (Exception e) {
  52. System.err.println("Error closing client socket: " + e.getMessage());
  53. }
  54. }
  55. }
  56. // Sortiermethode für die Zeichen im String
  57. private String sortCharacters(String input) {
  58. char[] chars = input.toCharArray();
  59. Arrays.sort(chars);
  60. return new String(chars);
  61. }
  62. }