I have the following code. And you can see its output below. As I think by javadoc socket.read
should never hang or whatever and this is an unexpected behavior.
Context con = new Context();
con.buf = ByteBuffer.allocate(1024);
log.trace("reading.. {}, {}, {}, {}, {}", socket.isConnected(), !socket.isBlocking(), socket.isOpen(), socket.keyFor(selector).isReadable(), socket.keyFor(selector).isValid());
FutureTask<Integer> readTask = new FutureTask<Integer>(
new Callable<Integer>() {
Context con;
Callable<Integer> setContext(Context con) {
this.con = con;
return this;
}
public Integer call() throws Exception{
int rd = socket.read(con.buf);
return Integer.valueOf(rd);
}
}.setContext(con)
);
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.submit(readTask);
int read = 0;
try {
read = readTask.get(5, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log.error("hello java");
System.exit(0);
}
(I do not need a futuretask there at all, but it was just to check my assumption about stucking in socket.read
method).
And here's the log output (notice that !socket.isBlocking()
is reversed, so it's showing it's in NON blocking mode):
reading.. true, true, true, true, true
hello java
this means after 5 seconds we still got nothing, socket is still opened, and nothing that could be wrong.
Please help me with that issue. Could it be something around socket's "keepalive" or OS or java or firewall (still I'm reading and writing at localhost only) issue?
This is how I got this socket:
SocketChannel socket = ((ServerSocketChannel) key.channel()).accept();
log.trace("accepted:{}", socket.getRemoteAddress());
socket.configureBlocking(false);
socket.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);