简体   繁体   English

Java SocketChannel:为什么wrap-flip-write不起作用但是wrap-write呢?

[英]Java SocketChannel : Why wrap-flip-write doesn't work but wrap-write does?

Assume we have a Java SocketChannel connected to a server which is waiting for incoming data: 假设我们有一个Java SocketChannel连接到等待传入数据的服务器:

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

And we send our request as below: 我们发送请求如下:

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);

The above code returns 0 which means it doesn't write any bytes to the channel ! 上面的代码返回0 ,这意味着它不会向通道写入任何字节!

But if I remove the buffer.flip() line, it will work fine and data is sent: 但是,如果我删除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);

Why is this ?! 为什么是这样 ?!

I figured out the issue myself, so I'm writing it here on StackOverflow to share the info and be useful for anyone else facing the same problem. 我自己想出了这个问题,所以我在StackOverflow上写StackOverflow来分享信息,并对面临同样问题的其他人有用。

According to the java-doc for ByteBuffer.wrap() : 根据ByteBuffer.wrap()java-doc

The new buffer's capacity and limit will be array.length , its position will be zero, and its mark will be undefined. 新缓冲区的容量和限制将是array.length ,它的位置将为零,其标记将是未定义的。

And the java-doc for Buffer.flip() says: Buffer.flip()java-doc说:

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. 如果定义了标记,则将其丢弃。

The answer is now clear: wrap() sets the buffer's position to zero, and flip() sets the buffer's limit to the current position (which is zero), and write(buffer) will start from position to limit which are both 0 , thus it writes nothing! 现在答案是明确的: wrap()将缓冲区的位置设置为零,而flip()将缓冲区的限制设置为当前位置(为零),而write(buffer)将从位置开始到限制,这两个都是0 ,因此它什么都没写!

wrap() delivers a buffer which is already flipped. wrap()提供已经翻转的缓冲区。 Flipping it again basically empties it from the point of view of write() or get(). 再次翻转它基本上会从write()或get()的角度清空它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM