I am trying to write a simple client server program in Java NIO.
Here is the code:
package org.lb;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;
public class Test {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Set<SelectionKey> selectionKeySet = selector.selectedKeys();
for (SelectionKey selectionKey : selectionKeySet) {
if (selectionKey.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
if (socketChannel == null) {
System.out.println("No connection...");
} else {
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("Connection done!");
}
}
if (selectionKey.isReadable()) {
System.out.println("isReadable");
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
socketChannel.close();
}
}
}
}
}
You can see that I call serverSocketChannel.accept() only when selectionKey.isAcceptable() returns true. So, I assume that serverSocketChannel.accept() should always return a valid SocketChannel instance, but sometimes it's returning null as well.
I am trying to send request using Postman, but the same case is with browser requests too.
Output with Postman single request
Connection done!
No connection...
isReadable
Connection done!
No connection...
isReadable
I expected that Connection done! is printed once, but it's printing twice. Also, why No connection... is printed?
Output with curl single request
Connection done!
isReadable
No connection...