Netty权威指南之文件传输

Dear 丶 2023-10-16 21:50 68阅读 0赞

本章相关知识点:

文件是最常见的数据源之一,在程序经常需要将数据存储到文件中,比如:图片文件、声音文件等数据文件。在实际使用中,文件都包含一个特定的格式,这个格式需要程序员根据需求进行设计。读取已有文件是需要熟悉对应文件格式,才能把数据从文件中正确的读取出来。

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

1、基于字节流的InputStream和OutputStram;

2、基于字符流的Reader和Writer;

通过NIO新提供的FileChannel类库可以方便地以“管道”方式对文件进行各种I/O操作,相比于传统以流方式进行的I/O操作有了很大的变化和改进。

本章主要学习目标

1、文件的基础知识

2、Netty文件传输开发

3、运行Netty 文件传输项目;

第一节:文件的基础知识

可以参考下面这边文章:

第二节:Netty文件传输开发

服务端源代码:

FileServer.java

  1. package com.nio.file;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;
  10. import io.netty.handler.codec.LineBasedFrameDecoder;
  11. import io.netty.handler.codec.string.StringDecoder;
  12. import io.netty.handler.codec.string.StringEncoder;
  13. import io.netty.util.CharsetUtil;
  14. /**
  15. * Created by vixuan-008 on 2015/6/25.
  16. */
  17. public class FileServer {
  18. public void run(int port) throws Exception {
  19. EventLoopGroup bossGroup = new NioEventLoopGroup();
  20. EventLoopGroup workerGroup = new NioEventLoopGroup();
  21. try {
  22. ServerBootstrap b = new ServerBootstrap();
  23. b.group(bossGroup, workerGroup)
  24. .channel(NioServerSocketChannel.class)
  25. .option(ChannelOption.SO_BACKLOG, 100)
  26. .childHandler(new ChannelInitializer<SocketChannel>() {
  27. /*
  28. * (non-Javadoc)
  29. *
  30. * @see
  31. * io.netty.channel.ChannelInitializer#initChannel(io
  32. * .netty.channel.Channel)
  33. */
  34. public void initChannel(SocketChannel ch)
  35. throws Exception {
  36. ch.pipeline().addLast(
  37. new StringEncoder(CharsetUtil.UTF_8),
  38. new LineBasedFrameDecoder(1024),
  39. new StringDecoder(CharsetUtil.UTF_8),
  40. new FileServerHandler());
  41. }
  42. });
  43. ChannelFuture f = b.bind(port).sync();
  44. System.out.println("Start file server at port : " + port);
  45. f.channel().closeFuture().sync();
  46. } finally {
  47. // 优雅停机
  48. bossGroup.shutdownGracefully();
  49. workerGroup.shutdownGracefully();
  50. }
  51. }
  52. public static void main(String[] args) throws Exception {
  53. int port = 17887;
  54. new FileServer().run(port);
  55. }
  56. }

FileServerHandler.java

  1. package com.nio.file;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.DefaultFileRegion;
  4. import io.netty.channel.FileRegion;
  5. import io.netty.channel.SimpleChannelInboundHandler;
  6. import java.io.File;
  7. import java.io.RandomAccessFile;
  8. /**
  9. * Created by vixuan-008 on 2015/6/25.
  10. */
  11. public class FileServerHandler extends SimpleChannelInboundHandler<String> {
  12. private static final String CR = System.getProperty("line.separator");
  13. /*
  14. * (non-Javadoc)
  15. *
  16. * @see
  17. * io.netty.channel.SimpleChannelInboundHandler#messageReceived(io.netty
  18. * .channel.ChannelHandlerContext, java.lang.Object)
  19. */
  20. public void messageReceived(ChannelHandlerContext ctx, String msg)
  21. throws Exception {
  22. File file = new File(msg);
  23. if (file.exists()) {
  24. if (!file.isFile()) {
  25. ctx.writeAndFlush("Not a file : " + file + CR);
  26. return;
  27. }
  28. ctx.write(file + " " + file.length() + CR);
  29. RandomAccessFile randomAccessFile = new RandomAccessFile(msg, "r");
  30. FileRegion region = new DefaultFileRegion(
  31. randomAccessFile.getChannel(), 0, randomAccessFile.length());
  32. ctx.write(region);
  33. ctx.writeAndFlush(CR);
  34. randomAccessFile.close();
  35. } else {
  36. ctx.writeAndFlush("File not found: " + file + CR);
  37. }
  38. }
  39. /*
  40. * (non-Javadoc)
  41. *
  42. * @see
  43. * io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel
  44. * .ChannelHandlerContext, java.lang.Throwable)
  45. */
  46. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
  47. throws Exception {
  48. ctx.close();
  49. }
  50. }

第三节:运行Netty 文件传输项目

启动文件服务器,打开CMD控制台,通过telnet命令连接到主机,如图所示:

Center

连接成功后,输入需要传输的文件路径:D:\network.xml,然后输入回车键,显示结果如图所示:

Center 1

发表评论

表情:
评论列表 (有 0 条评论,68人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Netty权威指南文件传输

    本章相关知识点: 文件是最常见的数据源之一,在程序经常需要将数据存储到文件中,比如:图片文件、声音文件等数据文件。在实际使用中,文件都包含一个特定的格式,这个格式需要程序员根

    相关 Netty权威指南AIO编程

    由JDK1.7提供的NIO2.0新增了异步的套接字通道,它是真正的异步I/O,在异步I/O操作的时候可以传递信号变量,当操作完成后会回调相关的方法,异步I/o也被称为AIO,对