gpt4 book ai didi

Java 套接字 channel : Why wrap-flip-write doesn't work but wrap-write does?

转载 作者:行者123 更新时间:2023-11-29 03:29:29 24 4
gpt4 key购买 nike

假设我们有一个 Java SocketChannel 连接到正在等待传入数据的服务器:

SocketChannel server = SocketChannel.open();
server.connect(new InetSocketAddress(ip, port));

然后我们发送如下请求:

byte[] request = "This is a request for server!".getBytes();
ByteBuffer buffer = ByteBuffer.wrap(request);
buffer.flip();
int write = 0;
while (buffer.hasRemaining())
write += server.write(buffer);
System.out.println(write);

上面的代码返回0,这意味着它没有向 channel 写入任何字节!

但如果我删除 buffer.flip() 行,它将正常工作并发送数据:

byte[] request = "This is a request for server!".getBytes();
ByteBuffer buffer = ByteBuffer.wrap(request);
int write = 0;
while (buffer.hasRemaining())
write += server.write(buffer);
System.out.println(write);

这是为什么?!

最佳答案

我自己解决了这个问题,所以我将它写在 StackOverflow 上以共享信息并对面临同样问题的其他人有用。

根据java-doc对于 ByteBuffer.wrap():

The new buffer's capacity and limit will be array.length, its position will be zero, and its mark will be undefined.

还有 java-doc对于 Buffer.flip() 说:

Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded.

现在答案很明确:wrap() 将缓冲区的位置设置为零,而 flip() 将缓冲区的限制设置为当前位置(为零) , 和 write(buffer) 将从 position 开始到 limit 都是 0,因此它什么都不写!

关于Java 套接字 channel : Why wrap-flip-write doesn't work but wrap-write does?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19117463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com