Magdalena, Luca-Marie, Melanie
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.

SorterServer.java 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package Praktikum4;
  2. import java.io.*;
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. public class SorterServer implements Runnable {
  8. public static void main(String[] args) {
  9. final int port = 12345;
  10. try (ServerSocket socket = new ServerSocket(port)) {
  11. while (true) {
  12. Socket client = socket.accept();
  13. Thread thread = new Thread(new SorterServer(client));
  14. thread.start();
  15. }
  16. } catch (Exception e) {
  17. System.err.println("Error: " + e.getMessage());
  18. }
  19. }
  20. private Socket socket;
  21. private SorterServer(Socket socket) {
  22. this.socket = socket;
  23. }
  24. @Override
  25. public void run() {
  26. try {
  27. String msg = receiveLine(this.socket);
  28. String ausgabe=sortAndCount(msg);
  29. sendLine(socket,ausgabe );
  30. }
  31. catch (Exception e) {};
  32. }
  33. public static String receiveLine(Socket socket) throws IOException {
  34. InputStream in = socket.getInputStream();
  35. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  36. return reader.readLine();
  37. }
  38. public static void sendLine(Socket socket, String line) throws IOException {
  39. OutputStream out = socket.getOutputStream();
  40. PrintWriter writer = new PrintWriter(out);
  41. writer.println(line);
  42. writer.flush();
  43. }
  44. public static String sortAndCount(String input) {
  45. Map<Character, Integer> charCountMap = new HashMap<>();
  46. for (char c : input.toCharArray()) {
  47. charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
  48. }
  49. StringBuilder sortedString = new StringBuilder();
  50. for (char c = 'a'; c <= 'z'; c++) {
  51. if (charCountMap.containsKey(c)) {
  52. int count = charCountMap.get(c);
  53. for (int i = 0; i < count; i++) {
  54. sortedString.append(c);
  55. }
  56. }
  57. }
  58. // Rückgabe der sortierten Zeichenkette
  59. return sortedString.toString();
  60. }
  61. }