-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDispatcher.java
More file actions
100 lines (81 loc) · 2.54 KB
/
Dispatcher.java
File metadata and controls
100 lines (81 loc) · 2.54 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
import java.nio.channels.*;
import java.awt.RenderingHints.Key;
import java.io.IOException;
import java.util.*; // for Set and Iterator
public class Dispatcher implements Runnable {
private Selector selector;
public Dispatcher() {
// create selector
try {
selector = Selector.open();
} catch (IOException ex) {
System.out.println("Cannot create selector.");
ex.printStackTrace();
System.exit(1);
} // end of catch
} // end of Dispatcher
public Selector selector() {
return selector;
}
/*
* public SelectionKey registerNewSelection(SelectableChannel channel,
* IChannelHandler handler, int ops) throws ClosedChannelException {
* SelectionKey key = channel.register(selector, ops); key.attach(handler);
* return key; } // end of registerNewChannel
*
* public SelectionKey keyFor(SelectableChannel channel) { return
* channel.keyFor(selector); }
*
* public void deregisterSelection(SelectionKey key) throws IOException {
* key.cancel(); }
*
* public void updateInterests(SelectionKey sk, int newOps) {
* sk.interestOps(newOps); }
*/
public void run() {
while (true) {
Debug.DEBUG("Enter selection");
try {
// check to see if any events
selector.select();
Debug.DEBUG("hhhhhh");
} catch (IOException ex) {
ex.printStackTrace();
break;
}
// readKeys is a set of ready events
Set<SelectionKey> readyKeys = selector.selectedKeys();
// create an iterator for the set
Iterator<SelectionKey> iterator = readyKeys.iterator();
// iterate over all events
Debug.DEBUG(readyKeys.size());
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
try {
if (key.isAcceptable()) { // a new connection is ready to be
IAcceptHandler aH = (IAcceptHandler) key.attachment();
aH.handleAccept(key);
} // end of isAcceptable
if (key.isReadable() || key.isWritable()) {
IReadWriteHandler rwH = (IReadWriteHandler) key.attachment();
if (key.isReadable()) {
rwH.handleRead(key);
} // end of if isReadable
if (key.isWritable()) {
rwH.handleWrite(key);
} // end of if isWritable
} // end of readwrite
} catch (IOException ex) {
Debug.DEBUG("Exception when handling key " + key);
key.cancel();
try {
key.channel().close();
// in a more general design, call have a handleException
} catch (IOException cex) {
}
} // end of catch
} // end of while (iterator.hasNext()) {
} // end of while (true)
} // end of run
}