OnJava8-Examples/network/MultiSimpleClient.java

69 lines
1.9 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// network/MultiSimpleClient.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-09-03 12:18:15 -06:00
// Testing MultiSimpleServer with multiple clients.
2015-06-15 17:47:35 -07:00
// {ValidateByHand}
package network;
2015-06-15 17:47:35 -07:00
import java.net.*;
import java.io.*;
import onjava.*;
2015-06-15 17:47:35 -07:00
2016-09-03 12:18:15 -06:00
class SimpleClientThread implements Runnable {
private InetAddress address;
2015-06-15 17:47:35 -07:00
private static int counter = 0;
private int id = counter++;
private static int threadcount = 0;
public static int threadCount() {
return threadcount;
}
2016-09-03 12:18:15 -06:00
public SimpleClientThread(InetAddress address) {
2015-06-15 17:47:35 -07:00
System.out.println("Making client " + id);
2016-09-03 12:18:15 -06:00
this.address = address;
2015-06-15 17:47:35 -07:00
threadcount++;
2016-09-03 12:18:15 -06:00
}
@Override
public void run() {
try (
Socket socket =
new Socket(address, MultiSimpleServer.PORT);
BufferedReader in =
2015-06-15 17:47:35 -07:00
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
2016-09-03 12:18:15 -06:00
PrintWriter out =
2015-06-15 17:47:35 -07:00
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
2016-09-03 12:18:15 -06:00
// Enable auto-flush:
socket.getOutputStream())), true)
) {
for (int i = 0; i < 25; i++) {
2015-06-15 17:47:35 -07:00
out.println("Client " + id + ": " + i);
String str = in.readLine();
System.out.println(str);
}
out.println("END");
2016-09-03 12:18:15 -06:00
} catch (IOException ex) {
throw new RuntimeException(ex);
2015-06-15 17:47:35 -07:00
} finally {
threadcount--; // Ending this thread
}
}
}
public class MultiSimpleClient {
static final int MAX_THREADS = 40;
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws IOException,
InterruptedException {
2015-06-15 17:47:35 -07:00
new TimedAbort(5); // Terminate after 5 seconds
2016-09-03 12:18:15 -06:00
InetAddress address = InetAddress.getByName(null);
2015-06-15 17:47:35 -07:00
while(true) {
2016-08-31 12:30:03 -06:00
if(SimpleClientThread.threadCount() < MAX_THREADS)
2016-09-03 12:18:15 -06:00
new SimpleClientThread(address);
2015-06-15 17:47:35 -07:00
Thread.sleep(100);
}
}
2015-09-07 11:44:36 -06:00
}