void sendFile(File file) throws Exception {
long length = file.length();
LOG.debug("Got request of sending file {} of length {}.",
file, length);
Message handshake = MessageBuilder.buildFileHeader(length);
byte[] bytes = handshake.toByteArray();
// Sends HANDSHAKE first before transferring actual file data, the
// HANDSHAKE will tell the peer's channel to prepare for the file
// transferring.
channel.writeAndFlush(Unpooled.wrappedBuffer(bytes)).sync();
ChannelHandler prepender = channel.pipeline().get("frameEncoder");
// Removes length prepender, we don't need this handler for file
// transferring.
channel.pipeline().remove(prepender);
// Adds ChunkedWriteHandler for file transferring.
ChannelHandler cwh = new ChunkedWriteHandler();
channel.pipeline().addLast(cwh);
// Begins file transferring.
RandomAccessFile raf = new RandomAccessFile(file, "r");
if (channel.pipeline().get(SslHandler.class) != null) {
// Zero-Copy file transferring is not supported for ssl.
channel.writeAndFlush(new ChunkedFile(raf, 0, length, 8912));
} else {
// Use Zero-Copy file transferring in non-ssl mode.
FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, length);
channel.writeAndFlush(region);
}
// Restores pipeline to original state.
channel.pipeline().remove(cwh);
channel.pipeline().addLast("frameEncoder", prepender);
}
NettyTransport.java 文件源码
java
阅读 34
收藏 0
点赞 0
评论 0
项目:jzab
作者:
评论列表
文章目录