Browse Source

Merge branch 'server' into 'main'

Server

See merge request fdai7332/java-chat!3
remotes/origin/feature/client/make-input-field-buttons-interactive
fdai7599 11 months ago
parent
commit
ce517c92ff
  1. 36
      src/main/java/ChatServer.java

36
src/main/java/ChatServer.java

@ -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();
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"); System.out.println("Accepted new Client");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); 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);
}
} }
Loading…
Cancel
Save