I am writting a simple HTTP server using Java NIO but got stuck quiet early. I have the following code:
Selector accept = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
InetAddress lh = InetAddress.getByName("127.0.0.1");
InetSocketAddress isa = new InetSocketAddress(lh, port);
ssc.socket().bind(isa);
SelectionKey acceptKey = ssc.register(accept,
SelectionKey.OP_ACCEPT);
while (accept.select() > 0) {
Set<SelectionKey> readyKeys = accept.selectedKeys();
Iterator<SelectionKey> i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey sk = i.next();
if (sk.isAcceptable()) {
System.out.println("Is acceptable");
ssc = (ServerSocketChannel) sk.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.register(accept, SelectionKey.OP_READ);
System.out.println("Registered new SocketChannel");
}
if (sk.isReadable()) {
SocketChannel sc = (SocketChannel) sk.channel();
ByteBuffer buffer = ByteBuffer.allocate(20000);
buffer.clear();
int bytesRead = sc.read(buffer);
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear();
}
i.remove();
}
}
Now if I open two tabs in a browser and navigate to localhost:8080 this will be the output of the application:
Is acceptable
Registered new SocketChannel
Is acceptable
Registered new SocketChannel
GET / HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Is acceptable
Registered new SocketChannel
Now I have two questions: 1) Why do I get an extra accept event at the beginning? 2) Why the second http request is not received? The connection is accepted, its SocketChannel is being registered within the selector. But the request body is not received. I know that there are many "empty" read events generated but none of them brings the request body.