我试图从java服务器应用程序发送文件(pdf/bpm/jpg/png)到java客户端应用程序。 该文件以块形式发送。但是,如何知道文件何时完全发送?Netty:如何确定文件是否已完整发送?
我的第一个想法是使用得到通知,如果文件已完全发送。但是由于它在文件仍在发送时也被触发,所以它是无用的。有关如何进行的任何建议?
客户端管道:
ChannelPipeline p = ch.pipeline();
p.addLast("FileChunkHandler", new FileChunkHandler());
服务器管道:
p.addLast("Encoder", new ObjectEncoder());
p.addLast("Decoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
p.addLast("chunkedWriteHandler", new ChunkedWriteHandler());
p.addLast("FileSenderHandler", new FileSenderHandler());
的FileChunkHandler在客户端:
public class FileChunkHandler extends SimpleChannelInboundHandler<ChunkedFile>{
private ObjectOutputStream oout = null;
@Override protected void channelRead0(ChannelHandlerContext ctx, ChunkedFile msg) throws Exception{
System.out.println("channelRead0");
if (oout == null){
FileOutputStream out = new FileOutputStream("/Users/user/Documents/tmp/test/bla.txt");
oout = new ObjectOutputStream(out);
}
ByteBuf buf = (ByteBuf)msg;
int numberOfReadableBytes = buf.readableBytes();
byte[] bytes = new byte[numberOfReadableBytes];
buf.readBytes(bytes);
oout.write(bytes, 0, bytes.length);
}
@Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{
System.out.println("channelReadComplete");
ctx.fireChannelReadComplete();
}
}
的FileSenderHandler在服务器上:
公共类FileSenderHandler扩展ChannelInboundHandlerAdapter {
@Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception{
File file = new File("/Users/user/Documents/tmp/test/test.txt");
RandomAccessFile raf = new RandomAccessFile(file, "r");
ChannelFuture sendFileFuture = null;
if (ctx.pipeline().get(SslHandler.class) == null) {
sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, raf.length()), ctx.newProgressivePromise());
ctx.flush();
} else {
sendFileFuture = ctx.writeAndFlush(file, ctx.newProgressivePromise());
}
sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
@Override
public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
if (total < 0) { // total unknown
System.err.println(future.channel() + " Transfer progress: " + progress);
} else {
System.err.println(future.channel() + " Transfer progress: " + progress + "/" + total);
}
}
@Override
public void operationComplete(ChannelProgressiveFuture future) {
System.err.println(future.channel() + " Transfer complete.");
}
});
ctx.fireChannelRegistered();
}
由于这种方法需要大量重构我们的代码,所以这不是一个选项... – KayJ