我正在使用 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
?
我想以非阻塞和异步的方式解决这个问题。
The completed
当读取数据块时,从 java 管理的线程异步调用方法。要重用 CompletionHandler:
// More data to read
ch.read(buffer, null, this); //here you pass the same CompletionHandler you are using
java 人员建议当您完成读取操作时(else
块)你应该使用另一个线程上下文。
该文件指出要避免在 a 内阻塞和长期运行CompletionHandler
,查看第33页http://openjdk.java.net/projects/nio/presentations/TS-4222.pdf
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)