OnJava8-Examples/network/MultiSimpleClient.java

88 lines
2.3 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: network/MultiSimpleClient.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-05-05 11:20:13 -07:00
// Client that tests the MultiSimpleServer
// by starting up multiple clients.
2015-05-31 18:34:12 -07:00
// {ValidateByHand}
2015-05-05 11:20:13 -07:00
import java.net.*;
import java.io.*;
2015-05-31 18:34:12 -07:00
import net.mindview.util.*;
2015-05-05 11:20:13 -07:00
class SimpleClientThread 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;
2015-05-31 18:34:12 -07:00
public static int threadCount() {
return threadcount;
2015-05-05 11:20:13 -07:00
}
public SimpleClientThread(InetAddress addr) {
System.out.println("Making client " + id);
threadcount++;
try {
2015-05-31 18:34:12 -07:00
socket =
2015-05-05 11:20:13 -07:00
new Socket(addr, MultiSimpleServer.PORT);
} catch(IOException e) {
2015-05-31 18:34:12 -07:00
// If the creation of the socket fails,
2015-05-27 23:30:19 -07:00
// nothing needs cleanup.
2015-05-05 11:20:13 -07:00
}
2015-05-31 18:34:12 -07:00
try {
in =
2015-05-05 11:20:13 -07:00
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Enable auto-flush:
2015-05-31 18:34:12 -07:00
out =
2015-05-05 11:20:13 -07:00
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())), true);
start();
} catch(IOException e) {
2015-05-31 18:34:12 -07:00
// The socket should be closed on any
// failures other than the socket
2015-05-05 11:20:13 -07:00
// constructor:
try {
socket.close();
} catch(IOException e2) {}
}
// Otherwise the socket will be closed by
// the run() method of the thread.
}
@Override
public void run() {
try {
for(int i = 0; i < 25; i++) {
out.println("Client " + id + ": " + i);
String str = in.readLine();
System.out.println(str);
}
out.println("END");
} catch(IOException e) {
} finally {
// Always close it:
try {
socket.close();
} catch(IOException e) {}
threadcount--; // Ending this thread
}
}
}
public class MultiSimpleClient {
static final int MAX_THREADS = 40;
2015-05-31 18:34:12 -07:00
public static void main(String[] args)
2015-05-05 11:20:13 -07:00
throws IOException, InterruptedException {
2015-05-31 18:34:12 -07:00
new TimedAbort(5); // Terminate after 5 seconds
InetAddress addr =
2015-05-05 11:20:13 -07:00
InetAddress.getByName(null);
while(true) {
2015-05-31 18:34:12 -07:00
if(SimpleClientThread.threadCount()
2015-05-05 11:20:13 -07:00
< MAX_THREADS)
new SimpleClientThread(addr);
2015-05-06 12:09:38 -07:00
Thread.sleep(100);
2015-05-05 11:20:13 -07:00
}
}
} ///:~