forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiSimpleClient.java
More file actions
68 lines (66 loc) · 1.91 KB
/
MultiSimpleClient.java
File metadata and controls
68 lines (66 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// network/MultiSimpleClient.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Testing MultiSimpleServer with multiple clients.
// {ValidateByHand}
package network;
import java.net.*;
import java.io.*;
import onjava.*;
class SimpleClientThread implements Runnable {
private InetAddress address;
private static int counter = 0;
private int id = counter++;
private static int threadcount = 0;
public static int threadCount() {
return threadcount;
}
public SimpleClientThread(InetAddress address) {
System.out.println("Making client " + id);
this.address = address;
threadcount++;
}
@Override
public void run() {
try (
Socket socket =
new Socket(address, MultiSimpleServer.PORT);
BufferedReader in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
// Enable auto-flush:
socket.getOutputStream())), true)
) {
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 ex) {
throw new RuntimeException(ex);
} finally {
threadcount--; // Ending this thread
}
}
}
public class MultiSimpleClient {
static final int MAX_THREADS = 40;
public static void
main(String[] args) throws IOException,
InterruptedException {
new TimedAbort(5); // Terminate after 5 seconds
InetAddress address = InetAddress.getByName(null);
while(true) {
if(SimpleClientThread.threadCount() < MAX_THREADS)
new SimpleClientThread(address);
Thread.sleep(100);
}
}
}