I am using Java 7 and AsynchronousSocketChannel
. I would like to read a request (e.g. HTTP POST
) but I'm struggling to come up with a nice solution to read the full request, if it's bigger than the size of the ByteBuffer
I'm using. E.g. if the ByteBuffer
is 4048 bytes and the HTTP POST contains an image that is larger than 4kB.
Is there any nice recursive solution or loop for this?
Here is my code for reading requests:
public void readRequest(final AsynchronousSocketChannel ch) {
final ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
final StringBuilder strBuilder = new StringBuilder();
final CharsetDecoder decoder = Charset.forName("US-ASCII").newDecoder();
ch.read(buffer, null, new CompletionHandler<Integer, Void>() {
public void completed(Integer bytes, Void att) {
buffer.flip();
try {
decoder.reset();
strBuilder.append(decoder.decode(buffer).toString());
} catch (CharacterCodingException e) {
e.printStackTrace();
}
buffer.clear();
// More data to read or send response
if(bytes != -1) {
// More data to read
ch.read(...);
} else {
// Create and send a response
}
}
public void failed(Throwable exc, Void att) {
exc.printStackTrace();
}
});
}
And where I have written:
// More data to read
ch.read(...);
it look like a good place for code reuse, but I can't come up with a nice solution. Is there any way I can reuse the CompletionHandler here? Any suggestion for reading a full request with a limited ByteBuffer
?
I would like to solve this in an non-blocking and asynchronous way.