import java.net.*; import java.io.*; class EchoClientThread extends Thread { private Socket socket; private BufferedReader in; private PrintWriter out; private static int counter = 0; private int id = ++counter; private static int threadcount = 0; public static int threadCount() { return threadcount; } public EchoClientThread(InetAddress addr, int PORT) { System.out.println("Making client " + id); threadcount++; try { socket = new Socket(addr, PORT); } catch(IOException e) { System.err.println("Socket failed"); } try { in = new BufferedReader( new InputStreamReader( socket.getInputStream())); // Enable auto-flush: out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())), true); start(); } catch(IOException e) { try { socket.close(); } catch(IOException e2) { System.err.println("Socket not closed"); } } } public void run() { try { for(int i = 1; i <= 5; i++) { out.println("Client " + id + ": " + i); String str = in.readLine(); System.out.println(str); try { sleep(10000); } catch(InterruptedException e) { System.err.println("Interrupted"); } } out.println("END"); } catch(IOException e) { System.err.println("IO Exception"); } finally { // Always close it: try { socket.close(); } catch(IOException e) { System.err.println("Socket not closed"); } threadcount--; // Ending this thread } } } public class MultiEchoClient { static final int MAX_THREADS = 5; public static void main(String[] args) throws IOException, InterruptedException { InetAddress addr = InetAddress.getByName(args[0]); int Sport = Integer.parseInt(args[1]); while(true) { if(EchoClientThread.threadCount() < MAX_THREADS) new EchoClientThread(addr, Sport); Thread.currentThread().sleep(1000); } } }