0

I am trying to get the response sent by the web server through Java NIO socketChannel. The read call of SocketChannel is not returning anything when it is in non-blocking

    clientSocket.configureBlocking(false);

When specified true, means blocking mode, then it is returning response. Someone saying that we should use Selector when non-blocking mode enabled. But I didn't find a way to implement this.

FYI, Following is the code snippet I am trying.

public static void main(String[] args) throws IOException, InterruptedException
{
      URL u = new URL("http://www.google.com");

      InetSocketAddress addr = new InetSocketAddress("www.google.com", 80);
      SocketChannel clientSocket = SocketChannel.open(addr);
      clientSocket.configureBlocking(false);

      byte[] message = new String("GET " + u.getFile() + " HTTP/1.0\r\n").getBytes();
      ByteBuffer writeBuff = ByteBuffer.wrap(message);
      clientSocket.write(writeBuff);      

      ByteBuffer  readBuff = MappedByteBuffer.allocate(1500);
      clientSocket.read(readBuff);

      while(clientSocket.read(readBuff) > 0)
      {
            System.out.println(new String(readBuff.array()).trim());
      }

      clientSocket.close();
}

Thanks in advance.

Suneel Kumar
  • 1,650
  • 2
  • 21
  • 31
pavannpg
  • 41
  • 2
  • 7

2 Answers2

0

You should use loops to read() and write() till the buffer has no remaining bytes when non-blocking mode.

0

There two problems in your code:

  1. the http request body is wrong. it needs additional "\r\n".
  2. the readBuff need to cleared each time after reading.

below code is a working version:

static void working() throws Exception {
    URL u = new URL("http://www.baidu.com");

    InetSocketAddress addr = new InetSocketAddress("www.baidu.com", 80);
    SocketChannel clientSocket = SocketChannel.open(addr);
    clientSocket.configureBlocking(false);

    byte[] message = new String("GET / HTTP/1.0\r\n\r\n").getBytes();
    ByteBuffer writeBuff = ByteBuffer.wrap(message);
    clientSocket.write(writeBuff);

    ByteBuffer readBuff = MappedByteBuffer.allocate(1500);
    while (clientSocket.read(readBuff) != -1) {
        System.out.println("Entring...");
        System.out.println(new String(readBuff.array()).trim());
        readBuff.clear();
    }

    clientSocket.close();
}

}

Notice, if it's http version 1.1, it will not break too. because it has a keeplive.

scugxl
  • 317
  • 4
  • 15