Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> it = keys.iterator();
SelectionKey key = null;
while (it.hasNext()) {
key = it.next();
it.remove(); //错误处
SocketChannel sc = (SocketChannel) key.channel();
if (key.isValid()) {
if (key.isConnectable()) {
if (sc.finishConnect()) {
sc.register(selector, SelectionKey.OP_READ);
doWrite(sc);
}
} else {
System.out.println("connect to server failed");
}
if (key.isReadable()) {
ByteBuffer readBuffer = ByteBuffer.allocate(CommonConstants.B1024);
int readLength = sc.read(readBuffer);
if (readLength > 0) {
readBuffer.flip();
byte[] dataBytes = new byte[readBuffer.remaining()];
readBuffer.get(dataBytes);
String result = new String(dataBytes, Charset.forName(CommonConstants.UTF_8));
System.out.println("received message from server [" + sc.getRemoteAddress()
+ "], contents: [" + result + "]");
this.stop = true;
} else if (readLength < 0) {
key.cancel();
sc.close();
}
}
}
}
selector.selectedKeys():
Keys may be removed from, but not directly added to, the selected-key set. Any attempt to add an object to the key set will cause an UnsupportedOperationException
to be thrown.
selector.keys():
The key set is not directly modifiable. A key is removed only after it has been cancelled and its channel has been deregistered. Any attempt to modify the key set will cause an UnsupportedOperationException
to be thrown.
所以解决思路就是把错误处换成selectedKeys()