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);注意参数值,false 为 非阻塞,true 为 阻塞。