我正在处理一个基于 JBoss Netty 编解码器的ICAP github 项目。我目前的问题可能源于我无法正确理解 netty 处理程序和 Httpchunks 以及缺乏编程技能,我不知道如何将返回的数据成功写入文件。到目前为止,基本上我的代码能够将内容推送到文件中,但无论是我丢失数据、未正确执行还是将其组合错误,文件总是损坏我不完全确定。代码如下。我希望有任何建议或帮助。提前致谢。
package ch.mimo.netty.example.icap.preview;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import ch.mimo.netty.handler.codec.icap.DefaultIcapResponse;
import ch.mimo.netty.handler.codec.icap.IcapChunk;
import ch.mimo.netty.handler.codec.icap.IcapChunkTrailer;
import ch.mimo.netty.handler.codec.icap.IcapRequest;
import ch.mimo.netty.handler.codec.icap.IcapResponse;
import ch.mimo.netty.handler.codec.icap.IcapResponseStatus;
import ch.mimo.netty.handler.codec.icap.IcapVersion;
public class IcapServerHandler extends SimpleChannelUpstreamHandler {
private boolean continueWasSent;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
Object msg = e.getMessage();
if(msg instanceof IcapRequest) {
IcapRequest request = (IcapRequest)e.getMessage();
System.out.println(request.toString());
} else if(msg instanceof IcapChunkTrailer) {
System.out.println(msg.toString());
if(!continueWasSent) {
continueWasSent = true;
// sending 100 continue in order to receive the rest of the message
IcapResponse response = new DefaultIcapResponse(IcapVersion.ICAP_1_0,IcapResponseStatus.CONTINUE);
ctx.getChannel().write(response);
} else {
// sending 204 No Content response
IcapResponse response = new DefaultIcapResponse(IcapVersion.ICAP_1_0,IcapResponseStatus.NO_CONTENT);
ctx.getChannel().write(response);
}
} else if(msg instanceof IcapChunk) {
IcapChunk request3 = (IcapChunk)e.getMessage();
System.out.println(request3.getContent().toString(Charset.defaultCharset()));
testfile = "C:\\Users\\dan\\Desktop\\iso\\netty\\" + output;
buffer = request3.getContent();
ByteBuffer nioBuffer = buffer.toByteBuffer();
FileOutputStream fos = new FileOutputStream(testfile);
FileChannel channel = fos.getChannel();
while (nioBuffer.hasRemaining()) {
channel.write(nioBuffer);
}
fos.flush();
fos.close();
System.out.println(msg);
}
}
}
另外,我应该说对于小文本文件,我能够在本地成功地重建文件。但是,当我尝试构建文件时使用较大的 .docx 文件时,我没有获得完整大小并且文件已损坏。在这一点上,我真的不确定下一步该尝试什么。