Question

Assume we have a Java SocketChannel connected to a server which is waiting for incoming data:

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 !

But if I remove the buffer.flip() line, it will work fine and data is sent:

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 ?!

Was it helpful?

Solution

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.

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

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

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

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!

OTHER TIPS

wrap() delivers a buffer which is already flipped. Flipping it again basically empties it from the point of view of write() or get().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top