-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalcServer.java
More file actions
100 lines (85 loc) · 2.1 KB
/
Copy pathCalcServer.java
File metadata and controls
100 lines (85 loc) · 2.1 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package threadbook.ch15;
import java.io.*;
import java.net.*;
import java.util.*;
public class CalcServer extends Object {
private ServerSocket ss;
private List workerList;
private Thread internalThread;
private volatile boolean noStopRequested;
public CalcServer(int port) throws IOException {
ss = new ServerSocket(port);
workerList = new LinkedList();
noStopRequested = true;
Runnable r = new Runnable() {
public void run() {
try {
runWork();
} catch ( Exception x ) {
// in case ANY exception slips through
x.printStackTrace();
}
}
};
internalThread = new Thread(r);
internalThread.start();
}
private void runWork() {
System.out.println(
"in CalcServer - ready to accept connections");
while ( noStopRequested ) {
try {
System.out.println(
"in CalcServer - about to block " +
"waiting for a new connection");
Socket sock = ss.accept();
System.out.println(
"in CalcServer - received new connection");
workerList.add(new CalcWorker(sock));
} catch ( IOException iox ) {
if ( noStopRequested ) {
iox.printStackTrace();
}
}
}
// stop all the workers that were created
System.out.println("in CalcServer - putting in a " +
"stop request to all the workers");
Iterator iter = workerList.iterator();
while ( iter.hasNext() ) {
CalcWorker worker = (CalcWorker) iter.next();
worker.stopRequest();
}
System.out.println("in CalcServer - leaving runWork()");
}
public void stopRequest() {
System.out.println(
"in CalcServer - entering stopRequest()");
noStopRequested = false;
internalThread.interrupt();
if ( ss != null ) {
try {
ss.close();
} catch ( IOException x ) {
// ignore
} finally {
ss = null;
}
}
}
public boolean isAlive() {
return internalThread.isAlive();
}
public static void main(String[] args) {
int port = 2001;
try {
CalcServer server = new CalcServer(port);
Thread.sleep(15000);
server.stopRequest();
} catch ( IOException x ) {
x.printStackTrace();
} catch ( InterruptedException x ) {
// ignore
}
}
}