Netty的入门-文件传输

在NIO提供类库之前,Java的所有文件操作分为两类:

1、基于字节流的InputStream和OutputStream

2、基于字符流的Writer和Reader


Netty在进行大文件传输或者码流过大的时候,使用ChunkedWriteHandler来解决传输过程中可能出现的内存溢出。


下面看看基于Netty的文件操作:

public class FileServer {

	public static void main(String[] args) {
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(boss, worker)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 100)
				.childHandler(new ChannelInitializer<SocketChannel>() {

					@Override
					protected void initChannel(SocketChannel ch)
							throws Exception {
						ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8),
								new LineBasedFrameDecoder(1024),
								new StringDecoder(CharsetUtil.UTF_8),
								new FileServerHandler());
					}
				});
			final int PORT = 8089;
			ChannelFuture feature = b.bind(PORT).sync();
			System.out.println("start file server at port: " + PORT);
			feature.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
	
	static class FileServerHandler extends SimpleChannelInboundHandler<String> {

		private static final String CR = System.getProperty("line.separator");
		
		@Override
		protected void channelRead0(ChannelHandlerContext ctx, String msg)
				throws Exception {
			File file = new File(msg);
			if (file.exists()) {
				if (!file.isFile()) {
					ctx.writeAndFlush("Not a file: " + file + CR);
					return;
				}
				ctx.write(file + " " + file.length() + CR);
				@SuppressWarnings("resource")
				RandomAccessFile randomAccessFile = new RandomAccessFile(msg, "r");
				FileRegion fileRegion = new DefaultFileRegion(randomAccessFile.getChannel(), 0, randomAccessFile.length());
				ctx.write(fileRegion);
				ctx.writeAndFlush(CR);
			} else {
				ctx.writeAndFlush("File not found: " + file + CR);
			}
		}
		
		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
				throws Exception {
			super.exceptionCaught(ctx, cause);
			ctx.close();
			cause.printStackTrace();
		}
		
	}
	

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值