我正在尝试将文件从java服务器应用程序发送到Java客户端应用程序。 该文件似乎是从服务器发送到客户端,因为我输出如下:
...
Transfer progress: 8459452
Transfer progress: 8459452 / 8459452
Transfer complete.
问题似乎在客户端。为服务器发送的每个块调用channelReadComplete
。但channelRead0
从未被调用过!从来没有调用基类中的channelRead
(在我的处理程序中没有被覆盖)。知道我的代码有什么问题吗?提前谢谢!
客户端管道:
ChannelPipeline p = ch.pipeline();
p.addLast("Encoder", new ObjectEncoder());
p.addLast( "Decoder", new ObjectDecoder( Integer.MAX_VALUE, ClassResolvers.cacheDisabled( null ) ));
p.addLast("chunkedWriteHandler", new ChunkedWriteHandler());
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>{
@Override protected void channelRead0(ChannelHandlerContext ctx, ChunkedFile msg) throws Exception{
System.out.println( "channelRead0 ++++");
}
@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/kathrinjennifer/Documents/tmp/test/test.mp3" );
RandomAccessFile raf = null;
long fileLength = 0;
try {
raf = new RandomAccessFile(file, "r");
} catch(IOException e){
e.printStackTrace();
}
ChannelFuture sendFileFuture = null;
ChunkedFile chunkedFile = new ChunkedFile( raf);
sendFileFuture = ctx.write( chunkedFile, ctx.newProgressivePromise());
ctx.flush();
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();
}
答案 0 :(得分:1)
您应该使用SimpleChannelInboundHandler<ByteBuf>
,因为您将收到字节。