我花了很强的时间,把这.起来。 我有以下法典:
if (selector.select(1000) <= 0) {
return;
}
Set<SelectionKey> selectionKeys = selector.selectedKeys();
for (SelectionKey key : selectionKeys) {
try {
SocketEventHandler handler = (SocketEventHandler) key.attachment();
if (key.isValid() && key.isAcceptable()) {
handler.becomesAcceptable(key);
}
if (key.isValid() && key.isReadable()) {
handler.becomesReadable(key);
}
if (key.isValid() && key.isWritable()) {
handler.becomesWritable(key);
}
if (key.isValid() && key.isConnectable()) {
handler.becomesConnectable(key);
}
} catch (IOException e) {
key.cancel();
}
}
selector.selectedKeys().clear();
The following Handler Code for案文如下:
synchronized public void becomesReadable(SelectionKey key) throws IOException {
ByteBuffer temporaryBuffer = ByteBuffer.allocate(DEFAULT_BYTE_BUFFER_SIZE);
temporaryBuffer.position(0);
int read = -1;
try {
read = channel.read(temporaryBuffer);
} catch (IOException e) {
prefixLogger.debug("Trace:", e);
close();
}
...
}
And that s the only point where the handler function is ever called. So if I ever get into the becomeReadable()
function the channel is in readable state, yet the call to read()
blocks without ever returning. Is there something I missed?