今天在學(xué)習(xí)java nio的時(shí)候碰到了一個(gè)奇怪的問(wèn)題,在客戶端斷開連接后,出現(xiàn)了不斷產(chǎn)生新OP_READ事件的問(wèn)題。
while(true){
if(selector.select(1000) == 0){ // 斷開連接后這里沒(méi)有延時(shí)的效果
System.out.println("==");
continue;
}
Iterator<SelectionKey> itr = selector.selectedKeys().iterator();
while (itr.hasNext()){
SelectionKey key = itr.next();
if(key.isAcceptable()){
handleAccept(key);
}
if(key.isReadable()){ // 斷開連接后這里會(huì)不斷判定為true
handleRead(key);
}
itr.remove();
}
}
原因就在于斷開連接后,為了讓你知道連接已斷開,所以會(huì)產(chǎn)生OP_READ事件。
那么該怎么判斷呢?
其實(shí)只要判斷一下byteBuffer的大小就可以了,當(dāng)byteBuffer的長(zhǎng)度小于0時(shí),說(shuō)明連接斷開了,那么把channel關(guān)閉就可以了。如下:
long readLength = sc.read(buf);
if(readLength < 0) sc.close();
參考:https://stackoverflow.com/questions/4139300/socketchannel-fires-isreadable-but-nothing-to-read