写NIO程序的时候遇到了SelectionKey.attachment()为空的问题,最后解决了,这里简单介绍下,希望能对其他人有帮助:
SelectionKey key = socketChannel.register(selector, SelectionKey.OP_CONNECT);
key.attach(group);
...
client.register(selector, SelectionKey.OP_READ);
if(key.isReadable()){
ChannelWorkerGroup group = (ChannelWorkerGroup) key.attachment();
的时候却报group为空。
原因是第二次register为OP_READ的时候没有带上第三个参数,改成这样就好了:
client.register(selector, SelectionKey.OP_READ, group);
if(key.isReadable()){
ChannelWorkerGroup group = (ChannelWorkerGroup) key.attachment();