我正在使用 Java 7 和AsynchronousSocketChannel
. 我想阅读一个请求(例如HTTP POST
),但我正在努力想出一个很好的解决方案来阅读完整的请求,如果它大于ByteBuffer
我正在使用的大小。例如,如果ByteBuffer
是 4048 字节并且 HTTP POST 包含大于 4kB 的图像。
有什么好的递归解决方案或循环吗?
这是我的阅读请求代码:
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();
}
});
}
我写的地方:
// More data to read
ch.read(...);
它看起来是代码重用的好地方,但我想不出一个好的解决方案。有什么办法可以在这里重用 CompletionHandler 吗?有什么建议可以阅读有限的完整请求ByteBuffer
吗?
我想以非阻塞和异步的方式解决这个问题。