[英]Java NIO. SocketChannel.read method all time return 0. Why?
[英]Java NIO. Why flip() method breaks my program?
下面的Java代码:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class Test {
public static void main(String args[]) throws IOException {
SocketChannel c = SocketChannel.open();
c.connect(new InetSocketAddress("google.com", 80));
ByteBuffer b = ByteBuffer.allocate(1024);
b.put("Request".getBytes());
System.out.println("Write: " + c.write(b));
int i;
while ((i = c.read(b)) != -1) {
System.out.println("Read: " + i);
b.clear();
}
}
}
实际结果:
写:1017读:0读:1024读:44
第一次,方法read()
读取0个字节。 这不酷。
我修改了代码:
b.put("Request".getBytes());
System.out.println("Write: " + c.write(b));
b.flip(); //I added this line
int i;
while ((i = c.read(b)) != -1) {
System.out.println("Read: " + i);
b.clear();
}
实际结果:
写:1017读:1024读:44
它看起来已经更好了。 感谢flip()
!
接下来,我将缓冲区字符串“ Request”放入缓冲区,该字符串的长度为7 ,但是方法write()
返回1017 。
哪种信息方法写给渠道?
我不确定,该方法写了字符串“ Request” 。
好的,我再次修改了代码:
b.put("Request".getBytes());
b.flip(); // I added this line
System.out.println("Write: " + c.write(b));
b.flip();
int i;
while ((i = c.read(b)) != -1) {
System.out.println("Read: " + i);
b.clear();
}
实际结果:
写:7
代码崩溃了...
为什么? 我的错误在哪里?
谢谢。
在从缓冲区读取数据之前 ,需要调用flip
方法。 flip()
方法,将缓冲区的limit
重置为当前位置,并将缓冲区的position
重置为0。
因此,如果ByteBuffer
有7个字节的数据,则您的位置(从0开始)为flip()
将其设为limit = 7
, position = 0
。 现在,可以进行阅读了。
这是一个关于如何最好地使用flip()
的示例:
public static final void nioCopy(ReadableByteChannel input, WritableByteChannel output) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
while (input.read(buffer) != -1) {
//Flip buffer
buffer.flip();
//Write to destination
output.write(buffer);
//Compact
buffer.compact();
}
//In case we have remainder
buffer.flip();
while (buffer.hasRemaining()) {
//Write to output
output.write(buffer);
}
}
尽管其名称(选择不当), flip()
还是不对称的。 您必须在从缓冲区进行的任何操作(写入或获取)之前调用它,然后再调用compact()
或clear()
将缓冲区放回可以读取或放置的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.