在客戶機端,讀碼:的java NIO的SocketChannel讀總是返回相同的數據
byte[] bytes = new byte[50]; //TODO should reuse buffer, for test only
ByteBuffer dst = ByteBuffer.wrap(bytes);
int ret = 0;
int readBytes = 0;
boolean fail = false;
try {
while ((ret = socketChannel.read(dst)) > 0) {
readBytes += ret;
System.out.println("read " + ret + " bytes from socket " + dst);
if (!dst.hasRemaining()) {
break;
}
}
int pos = dst.position();
byte[] data = new byte[pos];
dst.flip();
dst.get(data);
System.out.println("read data: " + StringUtil.toHexString(data));
} catch (Exception e) {
fail = true;
handler.onException(e);
}
問題是socketChannel.read()總返回正,我檢查返回緩衝器,該數據是重複N次,它喜歡低級套接字緩衝區的位置不會前進。任何想法?
感謝您的快速回放。這是連接到Netty服務器的套接字通道。我向服務器發送一個請求,服務器只返回了48個字節,代碼僅在selector.select()返回時執行,並且selectionKey可讀。所以我完全糊塗了。 – 2011-12-15 04:14:46