I am trying to write a TCP server that reads data sent by the client. I want to keep the client connection open after the read to be able to read any subsequent data sent.
The code I am executing is below :
while(true) {
try {
int keysSelected = selector.select();
System.out.println("keysSelected = " + keysSelected);
if (keysSelected < 1) {
continue;
}
} catch (IOException e) {
e.printStackTrace();
break;
}
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (key.isAcceptable()) {
processAcceptRequest(selector, key);
} else if (key.isReadable()) {
processQueryRequest(key);
}
}
}
The problem I am experiencing is that before any clients have connected, the select call on the selector blocks. After the first client connects and writes data to the server, select continuously returns a OP_READ key, even though there is no data to read? What am I doing wrong?
The code for the read is :
private void processQueryRequest(SelectionKey key) {
ByteBuffer byteBuffer = ByteBuffer.allocate(32);
SocketChannel clientChannel = (SocketChannel) key.channel();
try {
byteBuffer.clear();
while(clientChannel.read(byteBuffer) > 0) {
byteBuffer.flip();
Charset charset = Charset.forName("UTF-8");
CharBuffer charBuffer = charset.decode(byteBuffer);
System.out.println(charBuffer.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
Regards
Brian
You need to call
compact()after you callflip()and process the data you get. You’re never doing that, so you’re filling the buffer, soread()is returning zero, so you are returning to theselect()loop, but there is still pending data in the socket receive buffer.