java.nio.channels.IllegalBlockingModeException
相关错误代码:
- class Handler {
- public Handler(Selector selector, SocketChannel socketChannel) throws InterruptedException {
- try {
- SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // while (true) {
- // System.out.println("Handler");
- // Thread.sleep(1000);
- // }
- socketChannelMap.put(socketChannel.hashCode(), socketChannel);
- System.out.println("Handler end" + socketChannel.hashCode() + "," + socketChannelMap.size());
- }
- }
- SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);
必须设置通道为 非阻塞,才能向 Selector 注册。
解决方法:
在发生错误的语句前添加:
- socketChannel.configureBlocking(false);