|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.Arrays;
-
- public class DistributedSorterServer implements Runnable {
- private final Socket clientSocket;
-
- // Konstruktor
- public DistributedSorterServer(Socket clientSocket) {
- this.clientSocket = clientSocket;
- }
-
- public static void main(String[] args) {
- final int port = 12345;
-
- try (ServerSocket serverSocket = new ServerSocket(port)) {
- System.out.println("Distributed Sorter Server is running on port " + port);
-
- while (true) {
- // Warten auf neue Verbindung
- Socket client = serverSocket.accept();
- System.out.println("New client connected: " + client.getInetAddress());
-
- // Neuen Thread starten, um die Client-Anfrage zu bearbeiten
- Thread thread = new Thread(new DistributedSorterServer(client));
- thread.start();
- }
- } catch (Exception e) {
- System.err.println("Error: " + e.getMessage());
- }
- }
-
- @Override
- public void run() {
- try (
- BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
- PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)
- ) {
- String inputLine;
-
- // Verarbeite alle Nachrichten vom Client
- while ((inputLine = in.readLine()) != null) {
- System.out.println("Received: " + inputLine);
-
- // Sortiere die Buchstaben im String
- String sortedLine = sortCharacters(inputLine);
- System.out.println(inputLine + " -> " + sortedLine);
-
- // Antwort zurück an den Client senden
- out.println(sortedLine);
- }
- } catch (Exception e) {
- System.err.println("Error handling client: " + e.getMessage());
- } finally {
- try {
- clientSocket.close();
- System.out.println("Client disconnected.");
- } catch (Exception e) {
- System.err.println("Error closing client socket: " + e.getMessage());
- }
- }
- }
-
- // Sortiermethode für die Zeichen im String
- private String sortCharacters(String input) {
- char[] chars = input.toCharArray();
- Arrays.sort(chars);
- return new String(chars);
- }
- }
|