我有一个选择器帖子:http://www.copypastecode.com/83442/
它有一个它处理的ChangeRequests列表,然后阻塞,然后处理Keys。连接和发送方法是唯一将wakeup()发送到选择器的方法。
当我建立2个服务器并运行单独的select循环时,碰巧第二个服务器似乎没有阻塞select()。我这样说是因为没有日志消息打印,无论是在连接还是发送,在处理密钥时都没有。无限循环时,不会处理任何键。
我该如何解决这种情况?如果违背了使用非阻塞IO的目的。
protected void startSelectorThread() {
new Thread() {
public void run() {
log.debug("NIOThreadedConnection: Selector Thread started; " + serverSocketChannel);
selectorRunning = true;
while (selectorRunning == true) {
log.debug(".");
processChangeRequests();
blockForSelectorTraffic();
processSelectionKeys();
}
System.out.println("Selector Thread terminated");
nioServer.stoppedListening(null);
}
}.start();
}
protected void processChangeRequests() {
synchronized (pendingChanges) {
for(ChangeRequest change:pendingChanges) {
switch (change.type) {
case ChangeRequest.CHANGEOPS: {
SelectionKey key = change.socket.keyFor(socketSelector);
if (key == null) {
continue;
}
key.interestOps(change.ops);
continue;
}
// Client only:
case ChangeRequest.REGISTER: {
try {
log.debug("future connection with channel: " + change.socket);
change.socket.register(socketSelector, change.ops);
} catch (ClosedChannelException e) {
log.debug("closed channel(" + change.socket + ")");
}
continue;
}
}
}
pendingChanges.clear();
}
}
protected void blockForSelectorTraffic() {
try {
socketSelector.select();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void processSelectionKeys() {
Iterator<SelectionKey> selectedKeys = socketSelector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = selectedKeys.next();
log.debug("found a key: " + key);
selectedKeys.remove();
if (!key.isValid()) {
log.debug("key invalid: " + key);
continue;
}
try {
if (key.isAcceptable()) {
log.debug("accept with a ListenConnection: " + key);
try {
accept(key);
} catch (ClosedChannelException e) {
log.debug("closed server channel(" + key + ")");
}
} else if (key.isConnectable()) {
log.debug("finishing connection: " + key);
finishConnection(key);
} else if (key.isReadable()) {
log.debug("reading with key: " + key);
int bytesRead = read(key);
log.debug("read: " + bytesRead + " with key: " + key);
} else if (key.isWritable()) {
log.debug("writing with key: " + key);
int bytesWritten = write(key);
log.debug("write: " + bytesWritten + " with key: " + key);
}
} catch (IOException e) {
e.printStackTrace();
}
}
log.debug("all done with keys");
}
谢谢, 罗伯特