diff --git a/src/main/java/ChatServer.java b/src/main/java/ChatServer.java index 0fd0416..0c60774 100644 --- a/src/main/java/ChatServer.java +++ b/src/main/java/ChatServer.java @@ -2,31 +2,59 @@ import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; public class ChatServer { private ServerSocket serverSocket; + private List clients; // Liste, um alle verbundenen Clients zu verwalten public ChatServer(int port) { + clients = new CopyOnWriteArrayList<>(); // Verwende CopyOnWriteArrayList für die Thread-Sicherheit + try { serverSocket = new ServerSocket(port); System.out.println("Started ChatServer on port " + port); - Socket connectionToClient = serverSocket.accept(); - - System.out.println("Accepted new Client"); + while (true) { + System.out.println("waiting for new Client..."); + Socket connectionToClient = serverSocket.accept(); // Auf Verbindungen von Clients warten + ClientHandler client = new ClientHandler(this, connectionToClient); + clients.add(client); // Neuen Client zur Liste hinzufügen + System.out.println("Accepted new Client"); + } } catch (IOException e) { e.printStackTrace(); + } finally { + if (serverSocket != null) { + try { + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } } - - public void broadcastMessage(String s) { + // Methode, um eine Nachricht an alle verbundenen Clients zu senden + public void broadcastMessage(String message) { + System.out.println(message); + if (message != null) { + for (ClientHandler client : clients) { + client.sendMessage(message); // Nachricht an jeden Client senden + } + } } public static void main(String[] args) { - new ChatServer(3141); + new ChatServer(3141); // ChatServer auf Port 3141 starten (eventuell den Port flexibler noch wählen? falls belegt) } + // Methode, um einen Client aus der Liste der verbundenen Clients zu entfernen + public void removeClient(ClientHandler client) { + clients.remove(client); + } } \ No newline at end of file