import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class MultiServer { List clientList= new ArrayList<>(); void runServer() throws IOException { ServerSocket server = new ServerSocket(2000); System.out.println("Server started"); while(true) { Socket socket = server.accept(); System.out.println("New client "); ClientThread thread = new ClientThread(socket); clientList.add(thread); } } void sendToAll(String data){ clientList.forEach(t-> t.send(data)); } public static void main(String[] args) { try{ new MultiServer().runServer(); } catch (IOException e) { System.out.println(e); } } class ClientThread extends Thread { Socket socket; BufferedReader in; PrintStream out; ClientThread(Socket socket) throws IOException { this.socket = socket; this.in = new BufferedReader(new InputStreamReader(socket.getInputStream())); this.out = new PrintStream(socket.getOutputStream()); start(); } public void run() { try { while (isInterrupted() == false) { String data = in.readLine(); sendToAll(data); } } catch (IOException e) { e.printStackTrace(); } finally { try { System.in.close(); System.out.close(); socket.close(); } catch (IOException e) { System.err.println("Problem z zamknięciem strumieni lub połączenia"); e.printStackTrace(); } } } void send(String data) { System.out.println(data); } } }