Netty学习(十)-Netty文件上传

x33g5p2x  于2021-12-21 转载在 其他  
字(22.3k)|赞(0)|评价(0)|浏览(1029)

今天我们来完成一个使用netty进行文件传输的任务。在实际项目中,文件传输通常采用FTP或者HTTP附件的方式。事实上通过TCP Socket+File的方式进行文件传输也有一定的应用场景,尽管不是主流,但是掌握这种文件传输方式还是比较重要的,特别是针对两个跨主机的JVM进程之间进行持久化数据的相互交换。

而使用netty来进行文件传输也是利用netty天然的优势:零拷贝功能。很多同学都听说过netty的”零拷贝”功能,但是具体体现在哪里又不知道,下面我们就简要介绍下:

Netty的“零拷贝”主要体现在如下三个方面:

  1. Netty的接收和发送ByteBuffer采用DIRECT BUFFERS,使用堆外直接内存进行Socket读写,不需要进行字节缓冲区的二次拷贝。如果使用传统的堆内存(HEAP BUFFERS)进行Socket读写,JVM会将堆内存Buffer拷贝一份到直接内存中,然后才写入Socket中。相比于堆外直接内存,消息在发送过程中多了一次缓冲区的内存拷贝。

  2. Netty提供了组合Buffer对象,可以聚合多个ByteBuffer对象,用户可以像操作一个Buffer那样方便的对组合Buffer进行操作,避免了传统通过内存拷贝的方式将几个小Buffer合并成一个大的Buffer。

  3. Netty的文件传输采用了transferTo方法,它可以直接将文件缓冲区的数据发送到目标Channel,避免了传统通过循环write方式导致的内存拷贝问题。

具体的分析在此就不多做介绍,有兴趣的可以查阅相关文档。我们还是把重点放在文件传输上。Netty作为高性能的服务器端异步IO框架必然也离不开文件读写功能,我们可以使用netty模拟http的形式通过网页上传文件写入服务器,当然要使用http的形式那你也用不着netty!大材小用。netty4中如果想使用http形式上传文件你还得借助第三方jar包:okhttp。使用该jar完成http请求的发送。但是在netty5 中已经为我们写好了,我们可以直接调用netty5的API就可以实现。所以netty4和5的差别还是挺大的,至于使用哪个,那就看你们公司选择哪一个了!本文目前使用netty4来实现文件上传功能。下面我们上代码:

pom文件:

  1. <dependency>
  2. <groupId>io.netty</groupId>
  3. <artifactId>netty-all</artifactId>
  4. <version>4.1.5.Final</version>
  5. </dependency>

server端:

  1. import io.netty.bootstrap.ServerBootstrap;
  2. import io.netty.channel.Channel;
  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.nio.NioServerSocketChannel;
  9. import io.netty.handler.codec.serialization.ClassResolvers;
  10. import io.netty.handler.codec.serialization.ObjectDecoder;
  11. import io.netty.handler.codec.serialization.ObjectEncoder;
  12. public class FileUploadServer {
  13. public void bind(int port) throws Exception {
  14. EventLoopGroup bossGroup = new NioEventLoopGroup();
  15. EventLoopGroup workerGroup = new NioEventLoopGroup();
  16. try {
  17. ServerBootstrap b = new ServerBootstrap();
  18. b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<Channel>() {
  19. @Override
  20. protected void initChannel(Channel ch) throws Exception {
  21. ch.pipeline().addLast(new ObjectEncoder());
  22. ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingConcurrentResolver(null))); // 最大长度
  23. ch.pipeline().addLast(new FileUploadServerHandler());
  24. }
  25. });
  26. ChannelFuture f = b.bind(port).sync();
  27. f.channel().closeFuture().sync();
  28. } finally {
  29. bossGroup.shutdownGracefully();
  30. workerGroup.shutdownGracefully();
  31. }
  32. }
  33. public static void main(String[] args) {
  34. int port = 8080;
  35. if (args != null && args.length > 0) {
  36. try {
  37. port = Integer.valueOf(args[0]);
  38. } catch (NumberFormatException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. try {
  43. new FileUploadServer().bind(port);
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. }

server端handler:

  1. import io.netty.channel.ChannelHandlerContext;
  2. import io.netty.channel.ChannelInboundHandlerAdapter;
  3. import java.io.File;
  4. import java.io.RandomAccessFile;
  5. public class FileUploadServerHandler extends ChannelInboundHandlerAdapter {
  6. private int byteRead;
  7. private volatile int start = 0;
  8. private String file_dir = "D:";
  9. @Override
  10. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  11. if (msg instanceof FileUploadFile) {
  12. FileUploadFile ef = (FileUploadFile) msg;
  13. byte[] bytes = ef.getBytes();
  14. byteRead = ef.getEndPos();
  15. String md5 = ef.getFile_md5();//文件名
  16. String path = file_dir + File.separator + md5;
  17. File file = new File(path);
  18. RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
  19. randomAccessFile.seek(start);
  20. randomAccessFile.write(bytes);
  21. start = start + byteRead;
  22. if (byteRead > 0) {
  23. ctx.writeAndFlush(start);
  24. } else {
  25. randomAccessFile.close();
  26. ctx.close();
  27. }
  28. }
  29. }
  30. @Override
  31. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  32. cause.printStackTrace();
  33. ctx.close();
  34. }
  35. }

client端:

  1. import io.netty.bootstrap.Bootstrap;
  2. import io.netty.channel.Channel;
  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.nio.NioSocketChannel;
  9. import io.netty.handler.codec.serialization.ClassResolvers;
  10. import io.netty.handler.codec.serialization.ObjectDecoder;
  11. import io.netty.handler.codec.serialization.ObjectEncoder;
  12. import java.io.File;
  13. public class FileUploadClient {
  14. public void connect(int port, String host, final FileUploadFile fileUploadFile) throws Exception {
  15. EventLoopGroup group = new NioEventLoopGroup();
  16. try {
  17. Bootstrap b = new Bootstrap();
  18. b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<Channel>() {
  19. @Override
  20. protected void initChannel(Channel ch) throws Exception {
  21. ch.pipeline().addLast(new ObjectEncoder());
  22. ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
  23. ch.pipeline().addLast(new FileUploadClientHandler(fileUploadFile));
  24. }
  25. });
  26. ChannelFuture f = b.connect(host, port).sync();
  27. f.channel().closeFuture().sync();
  28. } finally {
  29. group.shutdownGracefully();
  30. }
  31. }
  32. public static void main(String[] args) {
  33. int port = 8080;
  34. if (args != null && args.length > 0) {
  35. try {
  36. port = Integer.valueOf(args[0]);
  37. } catch (NumberFormatException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. try {
  42. FileUploadFile uploadFile = new FileUploadFile();
  43. File file = new File("c:/1.txt");
  44. String fileMd5 = file.getName();// 文件名
  45. uploadFile.setFile(file);
  46. uploadFile.setFile_md5(fileMd5);
  47. uploadFile.setStarPos(0);// 文件开始位置
  48. new FileUploadClient().connect(port, "127.0.0.1", uploadFile);
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }

client端handler:

  1. import io.netty.channel.ChannelHandlerContext;
  2. import io.netty.channel.ChannelInboundHandlerAdapter;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.io.RandomAccessFile;
  6. public class FileUploadClientHandler extends ChannelInboundHandlerAdapter {
  7. private int byteRead;
  8. private volatile int start = 0;
  9. private volatile int lastLength = 0;
  10. public RandomAccessFile randomAccessFile;
  11. private FileUploadFile fileUploadFile;
  12. public FileUploadClientHandler(FileUploadFile ef) {
  13. if (ef.getFile().exists()) {
  14. if (!ef.getFile().isFile()) {
  15. System.out.println("Not a file :" + ef.getFile());
  16. return;
  17. }
  18. }
  19. this.fileUploadFile = ef;
  20. }
  21. public void channelActive(ChannelHandlerContext ctx) {
  22. try {
  23. randomAccessFile = new RandomAccessFile(fileUploadFile.getFile(), "r");
  24. randomAccessFile.seek(fileUploadFile.getStarPos());
  25. lastLength = (int) randomAccessFile.length() / 10;
  26. byte[] bytes = new byte[lastLength];
  27. if ((byteRead = randomAccessFile.read(bytes)) != -1) {
  28. fileUploadFile.setEndPos(byteRead);
  29. fileUploadFile.setBytes(bytes);
  30. ctx.writeAndFlush(fileUploadFile);
  31. } else {
  32. System.out.println("文件已经读完");
  33. }
  34. } catch (FileNotFoundException e) {
  35. e.printStackTrace();
  36. } catch (IOException i) {
  37. i.printStackTrace();
  38. }
  39. }
  40. @Override
  41. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  42. if (msg instanceof Integer) {
  43. start = (Integer) msg;
  44. if (start != -1) {
  45. randomAccessFile = new RandomAccessFile(fileUploadFile.getFile(), "r");
  46. randomAccessFile.seek(start);
  47. System.out.println("块儿长度:" + (randomAccessFile.length() / 10));
  48. System.out.println("长度:" + (randomAccessFile.length() - start));
  49. int a = (int) (randomAccessFile.length() - start);
  50. int b = (int) (randomAccessFile.length() / 10);
  51. if (a < b) {
  52. lastLength = a;
  53. }
  54. byte[] bytes = new byte[lastLength];
  55. System.out.println("-----------------------------" + bytes.length);
  56. if ((byteRead = randomAccessFile.read(bytes)) != -1 && (randomAccessFile.length() - start) > 0) {
  57. System.out.println("byte 长度:" + bytes.length);
  58. fileUploadFile.setEndPos(byteRead);
  59. fileUploadFile.setBytes(bytes);
  60. try {
  61. ctx.writeAndFlush(fileUploadFile);
  62. } catch (Exception e) {
  63. e.printStackTrace();
  64. }
  65. } else {
  66. randomAccessFile.close();
  67. ctx.close();
  68. System.out.println("文件已经读完--------" + byteRead);
  69. }
  70. }
  71. }
  72. }
  73. // @Override
  74. // public void channelRead(ChannelHandlerContext ctx, Object msg) throws
  75. // Exception {
  76. // System.out.println("Server is speek :"+msg.toString());
  77. // FileRegion filer = (FileRegion) msg;
  78. // String path = "E://Apk//APKMD5.txt";
  79. // File fl = new File(path);
  80. // fl.createNewFile();
  81. // RandomAccessFile rdafile = new RandomAccessFile(path, "rw");
  82. // FileRegion f = new DefaultFileRegion(rdafile.getChannel(), 0,
  83. // rdafile.length());
  84. //
  85. // System.out.println("This is" + ++counter + "times receive server:["
  86. // + msg + "]");
  87. // }
  88. // @Override
  89. // public void channelReadComplete(ChannelHandlerContext ctx) throws
  90. // Exception {
  91. // ctx.flush();
  92. // }
  93. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  94. cause.printStackTrace();
  95. ctx.close();
  96. }
  97. // @Override
  98. // protected void channelRead0(ChannelHandlerContext ctx, String msg)
  99. // throws Exception {
  100. // String a = msg;
  101. // System.out.println("This is"+
  102. // ++counter+"times receive server:["+msg+"]");
  103. // }
  104. }

我们还自定义了一个对象,用于统计文件上传进度的:

  1. import java.io.File;
  2. import java.io.Serializable;
  3. public class FileUploadFile implements Serializable {
  4. private static final long serialVersionUID = 1L;
  5. private File file;// 文件
  6. private String file_md5;// 文件名
  7. private int starPos;// 开始位置
  8. private byte[] bytes;// 文件字节数组
  9. private int endPos;// 结尾位置
  10. public int getStarPos() {
  11. return starPos;
  12. }
  13. public void setStarPos(int starPos) {
  14. this.starPos = starPos;
  15. }
  16. public int getEndPos() {
  17. return endPos;
  18. }
  19. public void setEndPos(int endPos) {
  20. this.endPos = endPos;
  21. }
  22. public byte[] getBytes() {
  23. return bytes;
  24. }
  25. public void setBytes(byte[] bytes) {
  26. this.bytes = bytes;
  27. }
  28. public File getFile() {
  29. return file;
  30. }
  31. public void setFile(File file) {
  32. this.file = file;
  33. }
  34. public String getFile_md5() {
  35. return file_md5;
  36. }
  37. public void setFile_md5(String file_md5) {
  38. this.file_md5 = file_md5;
  39. }
  40. }

输出为:

  1. 块儿长度:894
  2. 长度:8052
  3. -----------------------------894
  4. byte 长度:894
  5. 块儿长度:894
  6. 长度:7158
  7. -----------------------------894
  8. byte 长度:894
  9. 块儿长度:894
  10. 长度:6264
  11. -----------------------------894
  12. byte 长度:894
  13. 块儿长度:894
  14. 长度:5370
  15. -----------------------------894
  16. byte 长度:894
  17. 块儿长度:894
  18. 长度:4476
  19. -----------------------------894
  20. byte 长度:894
  21. 块儿长度:894
  22. 长度:3582
  23. -----------------------------894
  24. byte 长度:894
  25. 块儿长度:894
  26. 长度:2688
  27. -----------------------------894
  28. byte 长度:894
  29. 块儿长度:894
  30. 长度:1794
  31. -----------------------------894
  32. byte 长度:894
  33. 块儿长度:894
  34. 长度:900
  35. -----------------------------894
  36. byte 长度:894
  37. 块儿长度:894
  38. 长度:6
  39. -----------------------------6
  40. byte 长度:6
  41. 块儿长度:894
  42. 长度:0
  43. -----------------------------0
  44. 文件已经读完--------0
  45. Process finished with exit code 0

这样就实现了服务器端文件的上传,当然我们也可以使用http的形式。

server端:

  1. import io.netty.bootstrap.ServerBootstrap;
  2. import io.netty.channel.ChannelFuture;
  3. import io.netty.channel.EventLoopGroup;
  4. import io.netty.channel.nio.NioEventLoopGroup;
  5. import io.netty.channel.socket.nio.NioServerSocketChannel;
  6. public class HttpFileServer implements Runnable {
  7. private int port;
  8. public HttpFileServer(int port) {
  9. super();
  10. this.port = port;
  11. }
  12. @Override
  13. public void run() {
  14. EventLoopGroup bossGroup = new NioEventLoopGroup(1);
  15. EventLoopGroup workerGroup = new NioEventLoopGroup();
  16. ServerBootstrap serverBootstrap = new ServerBootstrap();
  17. serverBootstrap.group(bossGroup, workerGroup);
  18. serverBootstrap.channel(NioServerSocketChannel.class);
  19. //serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
  20. serverBootstrap.childHandler(new HttpChannelInitlalizer());
  21. try {
  22. ChannelFuture f = serverBootstrap.bind(port).sync();
  23. f.channel().closeFuture().sync();
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. } finally {
  27. bossGroup.shutdownGracefully();
  28. workerGroup.shutdownGracefully();
  29. }
  30. }
  31. public static void main(String[] args) {
  32. HttpFileServer b = new HttpFileServer(9003);
  33. new Thread(b).start();
  34. }
  35. }

Server端initializer:

  1. import io.netty.channel.ChannelInitializer;
  2. import io.netty.channel.ChannelPipeline;
  3. import io.netty.channel.socket.SocketChannel;
  4. import io.netty.handler.codec.http.HttpObjectAggregator;
  5. import io.netty.handler.codec.http.HttpServerCodec;
  6. import io.netty.handler.stream.ChunkedWriteHandler;
  7. public class HttpChannelInitlalizer extends ChannelInitializer<SocketChannel> {
  8. @Override
  9. protected void initChannel(SocketChannel ch) throws Exception {
  10. ChannelPipeline pipeline = ch.pipeline();
  11. pipeline.addLast(new HttpServerCodec());
  12. pipeline.addLast(new HttpObjectAggregator(65536));
  13. pipeline.addLast(new ChunkedWriteHandler());
  14. pipeline.addLast(new HttpChannelHandler());
  15. }
  16. }

server端hadler:

  1. import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
  2. import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
  3. import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
  4. import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
  5. import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
  6. import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
  7. import io.netty.buffer.Unpooled;
  8. import io.netty.channel.ChannelFuture;
  9. import io.netty.channel.ChannelFutureListener;
  10. import io.netty.channel.ChannelHandlerContext;
  11. import io.netty.channel.ChannelProgressiveFuture;
  12. import io.netty.channel.ChannelProgressiveFutureListener;
  13. import io.netty.channel.SimpleChannelInboundHandler;
  14. import io.netty.handler.codec.http.DefaultFullHttpResponse;
  15. import io.netty.handler.codec.http.DefaultHttpResponse;
  16. import io.netty.handler.codec.http.FullHttpRequest;
  17. import io.netty.handler.codec.http.FullHttpResponse;
  18. import io.netty.handler.codec.http.HttpChunkedInput;
  19. import io.netty.handler.codec.http.HttpHeaders;
  20. import io.netty.handler.codec.http.HttpResponse;
  21. import io.netty.handler.codec.http.HttpResponseStatus;
  22. import io.netty.handler.codec.http.HttpVersion;
  23. import io.netty.handler.codec.http.LastHttpContent;
  24. import io.netty.handler.stream.ChunkedFile;
  25. import io.netty.util.CharsetUtil;
  26. import io.netty.util.internal.SystemPropertyUtil;
  27. import java.io.File;
  28. import java.io.FileNotFoundException;
  29. import java.io.RandomAccessFile;
  30. import java.io.UnsupportedEncodingException;
  31. import java.net.URLDecoder;
  32. import java.util.regex.Pattern;
  33. import javax.activation.MimetypesFileTypeMap;
  34. public class HttpChannelHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
  35. public static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
  36. public static final String HTTP_DATE_GMT_TIMEZONE = "GMT";
  37. public static final int HTTP_CACHE_SECONDS = 60;
  38. @Override
  39. protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
  40. // 监测解码情况
  41. if (!request.getDecoderResult().isSuccess()) {
  42. sendError(ctx, BAD_REQUEST);
  43. return;
  44. }
  45. final String uri = request.getUri();
  46. final String path = sanitizeUri(uri);
  47. System.out.println("get file:"+path);
  48. if (path == null) {
  49. sendError(ctx, FORBIDDEN);
  50. return;
  51. }
  52. //读取要下载的文件
  53. File file = new File(path);
  54. if (file.isHidden() || !file.exists()) {
  55. sendError(ctx, NOT_FOUND);
  56. return;
  57. }
  58. if (!file.isFile()) {
  59. sendError(ctx, FORBIDDEN);
  60. return;
  61. }
  62. RandomAccessFile raf;
  63. try {
  64. raf = new RandomAccessFile(file, "r");
  65. } catch (FileNotFoundException ignore) {
  66. sendError(ctx, NOT_FOUND);
  67. return;
  68. }
  69. long fileLength = raf.length();
  70. HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  71. HttpHeaders.setContentLength(response, fileLength);
  72. setContentTypeHeader(response, file);
  73. //setDateAndCacheHeaders(response, file);
  74. if (HttpHeaders.isKeepAlive(request)) {
  75. response.headers().set("CONNECTION", HttpHeaders.Values.KEEP_ALIVE);
  76. }
  77. // Write the initial line and the header.
  78. ctx.write(response);
  79. // Write the content.
  80. ChannelFuture sendFileFuture =
  81. ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
  82. //sendFuture用于监视发送数据的状态
  83. sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
  84. @Override
  85. public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
  86. if (total < 0) { // total unknown
  87. System.err.println(future.channel() + " Transfer progress: " + progress);
  88. } else {
  89. System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
  90. }
  91. }
  92. @Override
  93. public void operationComplete(ChannelProgressiveFuture future) {
  94. System.err.println(future.channel() + " Transfer complete.");
  95. }
  96. });
  97. // Write the end marker
  98. ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
  99. // Decide whether to close the connection or not.
  100. if (!HttpHeaders.isKeepAlive(request)) {
  101. // Close the connection when the whole content is written out.
  102. lastContentFuture.addListener(ChannelFutureListener.CLOSE);
  103. }
  104. }
  105. @Override
  106. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  107. cause.printStackTrace();
  108. if (ctx.channel().isActive()) {
  109. sendError(ctx, INTERNAL_SERVER_ERROR);
  110. }
  111. ctx.close();
  112. }
  113. private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");
  114. private static String sanitizeUri(String uri) {
  115. // Decode the path.
  116. try {
  117. uri = URLDecoder.decode(uri, "UTF-8");
  118. } catch (UnsupportedEncodingException e) {
  119. throw new Error(e);
  120. }
  121. if (!uri.startsWith("/")) {
  122. return null;
  123. }
  124. // Convert file separators.
  125. uri = uri.replace('/', File.separatorChar);
  126. // Simplistic dumb security check.
  127. // You will have to do something serious in the production environment.
  128. if (uri.contains(File.separator + '.') || uri.contains('.' + File.separator) || uri.startsWith(".") || uri.endsWith(".")
  129. || INSECURE_URI.matcher(uri).matches()) {
  130. return null;
  131. }
  132. // Convert to absolute path.
  133. return SystemPropertyUtil.get("user.dir") + File.separator + uri;
  134. }
  135. private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
  136. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
  137. response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
  138. // Close the connection as soon as the error message is sent.
  139. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
  140. }
  141. /** * Sets the content type header for the HTTP Response * * @param response * HTTP response * @param file * file to extract content type */
  142. private static void setContentTypeHeader(HttpResponse response, File file) {
  143. MimetypesFileTypeMap m = new MimetypesFileTypeMap();
  144. String contentType = m.getContentType(file.getPath());
  145. if (!contentType.equals("application/octet-stream")) {
  146. contentType += "; charset=utf-8";
  147. }
  148. response.headers().set(CONTENT_TYPE, contentType);
  149. }
  150. }

client端:

  1. import io.netty.bootstrap.Bootstrap;
  2. import io.netty.channel.ChannelFuture;
  3. import io.netty.channel.ChannelInitializer;
  4. import io.netty.channel.ChannelOption;
  5. import io.netty.channel.EventLoopGroup;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioSocketChannel;
  9. import io.netty.handler.codec.http.DefaultFullHttpRequest;
  10. import io.netty.handler.codec.http.HttpHeaders;
  11. import io.netty.handler.codec.http.HttpMethod;
  12. import io.netty.handler.codec.http.HttpRequestEncoder;
  13. import io.netty.handler.codec.http.HttpResponseDecoder;
  14. import io.netty.handler.codec.http.HttpVersion;
  15. import io.netty.handler.stream.ChunkedWriteHandler;
  16. import java.net.URI;
  17. public class HttpDownloadClient {
  18. /** * 下载http资源 向服务器下载直接填写要下载的文件的相对路径 * (↑↑↑建议只使用字母和数字对特殊字符对字符进行部分过滤可能导致异常↑↑↑) * 向互联网下载输入完整路径 * @param host 目的主机ip或域名 * @param port 目标主机端口 * @param url 文件路径 * @param local 本地存储路径 * @throws Exception */
  19. public void connect(String host, int port, String url, final String local) throws Exception {
  20. EventLoopGroup workerGroup = new NioEventLoopGroup();
  21. try {
  22. Bootstrap b = new Bootstrap();
  23. b.group(workerGroup);
  24. b.channel(NioSocketChannel.class);
  25. b.option(ChannelOption.SO_KEEPALIVE, true);
  26. b.handler(new ChildChannelHandler(local));
  27. // Start the client.
  28. ChannelFuture f = b.connect(host, port).sync();
  29. URI uri = new URI(url);
  30. DefaultFullHttpRequest request = new DefaultFullHttpRequest(
  31. HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
  32. // 构建http请求
  33. request.headers().set(HttpHeaders.Names.HOST, host);
  34. request.headers().set(HttpHeaders.Names.CONNECTION,
  35. HttpHeaders.Values.KEEP_ALIVE);
  36. request.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
  37. request.content().readableBytes());
  38. // 发送http请求
  39. f.channel().write(request);
  40. f.channel().flush();
  41. f.channel().closeFuture().sync();
  42. } finally {
  43. workerGroup.shutdownGracefully();
  44. }
  45. }
  46. private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
  47. String local;
  48. public ChildChannelHandler(String local) {
  49. this.local = local;
  50. }
  51. @Override
  52. protected void initChannel(SocketChannel ch) throws Exception {
  53. // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
  54. ch.pipeline().addLast(new HttpResponseDecoder());
  55. // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
  56. ch.pipeline().addLast(new HttpRequestEncoder());
  57. ch.pipeline().addLast(new ChunkedWriteHandler());
  58. ch.pipeline().addLast(new HttpDownloadHandler(local));
  59. }
  60. }
  61. public static void main(String[] args) throws Exception {
  62. HttpDownloadClient client = new HttpDownloadClient();
  63. //client.connect("127.0.0.1", 9003,"/file/pppp/1.doc","1.doc");
  64. // client.connect("zlysix.gree.com", 80, "http://zlysix.gree.com/HelloWeb/download/20m.apk", "20m.apk");
  65. client.connect("www.ghost64.com", 80, "http://www.ghost64.com/qqtupian/zixunImg/local/2017/05/27/1495855297602.jpg", "1495855297602.jpg");
  66. }
  67. }

client端handler:

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.channel.ChannelInboundHandlerAdapter;
  6. import io.netty.handler.codec.http.HttpContent;
  7. //import io.netty.handler.codec.http.HttpHeaders;
  8. import io.netty.handler.codec.http.HttpResponse;
  9. import io.netty.handler.codec.http.LastHttpContent;
  10. import io.netty.util.internal.SystemPropertyUtil;
  11. /** * @Author:yangyue * @Description: * @Date: Created in 9:15 on 2017/5/28. */
  12. public class HttpDownloadHandler extends ChannelInboundHandlerAdapter {
  13. private boolean readingChunks = false; // 分块读取开关
  14. private FileOutputStream fOutputStream = null;// 文件输出流
  15. private File localfile = null;// 下载文件的本地对象
  16. private String local = null;// 待下载文件名
  17. private int succCode;// 状态码
  18. public HttpDownloadHandler(String local) {
  19. this.local = local;
  20. }
  21. @Override
  22. public void channelRead(ChannelHandlerContext ctx, Object msg)
  23. throws Exception {
  24. if (msg instanceof HttpResponse) {// response头信息
  25. HttpResponse response = (HttpResponse) msg;
  26. succCode = response.getStatus().code();
  27. if (succCode == 200) {
  28. setDownLoadFile();// 设置下载文件
  29. readingChunks = true;
  30. }
  31. // System.out.println("CONTENT_TYPE:"
  32. // + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
  33. }
  34. if (msg instanceof HttpContent) {// response体信息
  35. HttpContent chunk = (HttpContent) msg;
  36. if (chunk instanceof LastHttpContent) {
  37. readingChunks = false;
  38. }
  39. ByteBuf buffer = chunk.content();
  40. byte[] dst = new byte[buffer.readableBytes()];
  41. if (succCode == 200) {
  42. while (buffer.isReadable()) {
  43. buffer.readBytes(dst);
  44. fOutputStream.write(dst);
  45. buffer.release();
  46. }
  47. if (null != fOutputStream) {
  48. fOutputStream.flush();
  49. }
  50. }
  51. }
  52. if (!readingChunks) {
  53. if (null != fOutputStream) {
  54. System.out.println("Download done->"+ localfile.getAbsolutePath());
  55. fOutputStream.flush();
  56. fOutputStream.close();
  57. localfile = null;
  58. fOutputStream = null;
  59. }
  60. ctx.channel().close();
  61. }
  62. }
  63. /** * 配置本地参数,准备下载 */
  64. private void setDownLoadFile() throws Exception {
  65. if (null == fOutputStream) {
  66. local = SystemPropertyUtil.get("user.dir") + File.separator +local;
  67. //System.out.println(local);
  68. localfile = new File(local);
  69. if (!localfile.exists()) {
  70. localfile.createNewFile();
  71. }
  72. fOutputStream = new FileOutputStream(localfile);
  73. }
  74. }
  75. @Override
  76. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
  77. throws Exception {
  78. System.out.println("管道异常:" + cause.getMessage());
  79. cause.printStackTrace();
  80. ctx.channel().close();
  81. }
  82. }

这里客户端我放的是网络连接,下载的是一副图片,启动服务端和客户端就可以看到这个图片被下载到了工程的根目录下。

相关文章