-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoller.java
More file actions
79 lines (52 loc) · 1.55 KB
/
Copy pathPoller.java
File metadata and controls
79 lines (52 loc) · 1.55 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
package tinyTCPServer.net;
import tinyTCPServer.net.*;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.*;
public class Poller {
private Selector selector_;
private List<TcpChannel> activeChannels_ = null;
public Poller() throws IOException {
this.selector_ = Selector.open();
}
public void poll() throws IOException {
int num = this.selector_.select();
this.activeChannels_ = new ArrayList<TcpChannel>();
if (num > 0) {
Set<SelectionKey> selectedKeys = this.selector_.selectedKeys();
for (Iterator<SelectionKey> i = selectedKeys.iterator(); i
.hasNext();) {
SelectionKey k = i.next();
i.remove();
TcpChannel attachement = (TcpChannel) k.attachment();
TcpChannel channel;
if (null != attachement) {// for old channel
channel = new TcpChannel(attachement);
} else {// for new channel
channel = new TcpChannel(k);
}
this.activeChannels_.add(channel);
}
}
}
public void processActiveChannels(MessageProcessor msgProcessor) {
for (TcpChannel chan : this.activeChannels_) {
chan.processEvent(msgProcessor);
}
}
public void wakeUp() {
this.selector_.wakeup();
}
public void registerChannel(SocketChannel acceptedSocketChannel) {
try {
acceptedSocketChannel
.register(this.selector_, SelectionKey.OP_READ);
} catch (ClosedChannelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}