-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeWatcher.java
More file actions
54 lines (46 loc) · 1.36 KB
/
TimeWatcher.java
File metadata and controls
54 lines (46 loc) · 1.36 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
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class TimeWatcher implements Runnable {
private Selector Monitoredselector;
public TimeWatcher (Selector s) {
Monitoredselector = s;
}
@Override
public void run() {
Set<SelectionKey> readyKeys;
synchronized (this) {
readyKeys = Monitoredselector.selectedKeys();
}
Iterator<SelectionKey> iterator = readyKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
if (key.isReadable() && !key.isWritable()) {
GetRequestHandler rwH = (GetRequestHandler) key.attachment();
long WaitingTime = rwH.livingTime();
if (WaitingTime > 3000) {
synchronized (key) {
try {
SocketChannel client = (SocketChannel)key.channel();
ByteBuffer outBuffer = ByteBuffer.allocate(4096);
byte[] error = coding.encoding("TimeOut");
outBuffer.put(error);
client.write(outBuffer);
client.close();
key.cancel();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
};
}