|
@ -2,31 +2,59 @@ |
|
|
import java.io.IOException; |
|
|
import java.io.IOException; |
|
|
import java.net.ServerSocket; |
|
|
import java.net.ServerSocket; |
|
|
import java.net.Socket; |
|
|
import java.net.Socket; |
|
|
|
|
|
import java.util.List; |
|
|
|
|
|
import java.util.concurrent.CopyOnWriteArrayList; |
|
|
|
|
|
|
|
|
public class ChatServer { |
|
|
public class ChatServer { |
|
|
private ServerSocket serverSocket; |
|
|
private ServerSocket serverSocket; |
|
|
|
|
|
private List<ClientHandler> clients; // Liste, um alle verbundenen Clients zu verwalten |
|
|
|
|
|
|
|
|
public ChatServer(int port) { |
|
|
public ChatServer(int port) { |
|
|
|
|
|
clients = new CopyOnWriteArrayList<>(); // Verwende CopyOnWriteArrayList für die Thread-Sicherheit |
|
|
|
|
|
|
|
|
try { |
|
|
try { |
|
|
serverSocket = new ServerSocket(port); |
|
|
serverSocket = new ServerSocket(port); |
|
|
System.out.println("Started ChatServer on port " + 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) { |
|
|
} catch (IOException e) { |
|
|
e.printStackTrace(); |
|
|
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) { |
|
|
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); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
} |
|
|
} |