Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NIO. SocketChannel.read method all time return 0. Why?

I try understand how works java NIO. In particular, how works SocketChannel.

I wrote code below:

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;

public class Test {

    public static void main(String[] args) throws IOException {

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("google.com", 80));

        while (!socketChannel.finishConnect()) {
            // wait, or do something else...
        }

        String newData = "Some String...";

        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        buf.put(newData.getBytes());

        buf.flip();

        while (buf.hasRemaining()) {
            System.out.println(socketChannel.write(buf));
        }

        buf.clear().flip();

        int bytesRead;

        while ((bytesRead = socketChannel.read(buf)) != -1) {

            System.out.println(bytesRead);

        }

    }

}
  1. I try connect to google server.
  2. Send request to the server;
  3. Read answer from the server.

but, method socketChannel.read(buf) all time return 0 and performs infinitely.

Where I made mistake??

like image 202
user471011 Avatar asked Mar 05 '26 14:03

user471011


1 Answers

Because NIO SocektChannel will not block until the data is available for read. i.e, Non Blocking Channel can return 0 on read() operation.

That is why while using NIO you should be using java.nio.channels.Selector which gives you read notification on channel if the data is available.

On the otherhand, blocking channel will wait till the data is available and return how much data is available. i.e, Blocking channel will never return 0 on read() operation.

You can read more about NIO here:

  • http://tutorials.jenkov.com/java-nio/index.html
  • http://java.sun.com/developer/technicalArticles/releases/nio/
  • https://www.ibm.com/developerworks/java/tutorials/j-nio/section2.html
like image 66
Ramesh PVK Avatar answered Mar 07 '26 05:03

Ramesh PVK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!