本次是利用TCP在客户端发送文件流,服务端就接收流,写入相应的文件。

实验的源文件是一个图片,假设地址是D:\\Koala.jpg,接收保存后的图片为D:\\test.jpg
原理就是将文件读取成byte,通过bytebuffer发送即可

客户端
  1. package net.xjdsz.file;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.*;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioSocketChannel;
  9. import java.io.ByteArrayOutputStream;
  10. import java.io.FileInputStream;
  11. import java.io.InputStream;
  12. /**
  13. * Created by dingshuo on 2017/7/6.
  14. */
  15. public class UploadClient {
  16. public static void main(String[] args) throws Exception{
  17. UploadClient client=new UploadClient();
  18. client.connect();
  19. }
  20. public void connect(){
  21. EventLoopGroup group=new NioEventLoopGroup();
  22. try{
  23. Bootstrap b=new Bootstrap();
  24. b.group(group).channel(NioSocketChannel.class)
  25. .option(ChannelOption.TCP_NODELAY,true)
  26. .handler(new ChannelInitializer<SocketChannel>() {
  27. @Override
  28. protected void initChannel(SocketChannel ch) throws Exception {
  29. ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
  30. @Override
  31. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  32. ByteBuf msg;
  33. InputStream in = new FileInputStream("D:\\Koala.jpg");
  34. ByteArrayOutputStream out = new ByteArrayOutputStream();
  35. byte[] buffer = new byte[1024 * 100];
  36. int n = 0;
  37. while ((n = in.read(buffer)) != -1) {
  38. msg= Unpooled.buffer(buffer.length);
  39. //这里读取到多少,就发送多少,是为了防止最后一次读取没法满填充buffer,
  40. //导致将buffer中的处于尾部的上一次遗留数据也发送走
  41. msg.writeBytes(buffer,0,n);
  42. ctx.writeAndFlush(msg);
  43. msg.clear();
  44. }
  45. System.out.println(n);
  46. }
  47. });
  48. }
  49. });
  50. ChannelFuture f=b.connect("127.0.0.1",20000).sync();
  51. f.channel().closeFuture().sync();
  52. }catch (Exception e){
  53. }finally {
  54. group.shutdownGracefully();
  55. }
  56. }
  57. }

服务端
  1. package net.xjdsz.file;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.*;
  5. import io.netty.channel.nio.NioEventLoopGroup;
  6. import io.netty.channel.socket.SocketChannel;
  7. import io.netty.channel.socket.nio.NioServerSocketChannel;
  8. import io.netty.handler.logging.LogLevel;
  9. import io.netty.handler.logging.LoggingHandler;
  10. import java.io.File;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. /**
  14. * Created by dingshuo on 2017/7/6.
  15. */
  16. public class UploadServer {
  17. public void bind(int port) throws Exception{
  18. EventLoopGroup bossGroup=new NioEventLoopGroup();
  19. EventLoopGroup workerGroup=new NioEventLoopGroup();
  20. try{
  21. ServerBootstrap b=new ServerBootstrap();
  22. b.group(bossGroup,workerGroup)
  23. .channel(NioServerSocketChannel.class)
  24. .option(ChannelOption.SO_BACKLOG,1024)
  25. .handler(new LoggingHandler(LogLevel.INFO))
  26. .childHandler(new ChannelInitializer<SocketChannel>() {
  27. @Override
  28. protected void initChannel(SocketChannel ch) throws Exception {
  29. ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
  30. @Override
  31. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  32. super.channelActive(ctx);
  33. }
  34. @Override
  35. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  36. super.channelInactive(ctx);
  37. }
  38. @Override
  39. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  40. String path="D:\\test.jpg";
  41. File file=new File(path);
  42. if(!file.exists()){
  43. file.createNewFile();
  44. }
  45. FileOutputStream fos=new FileOutputStream(file,true);
  46. // BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(fos);
  47. ByteBuf buf=(ByteBuf)msg;
  48. byte[] bytes=new byte[buf.readableBytes()];
  49. buf.readBytes(bytes);
  50. System.out.println("本次接收内容长度:" + bytes.length);
  51. try {
  52. // bufferedOutputStream.write(bytes, 0, bytes.length);
  53. // buf.release();
  54. fos.write(bytes);
  55. fos.flush();
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. }
  59. }
  60. });
  61. }
  62. });
  63. //绑定端口,同步等待成功
  64. ChannelFuture f=b.bind(port).sync();
  65. //等待服务端监听端口关闭
  66. f.channel().closeFuture().sync();
  67. }finally {
  68. //退出,释放资源
  69. bossGroup.shutdownGracefully();
  70. workerGroup.shutdownGracefully();
  71. }
  72. }
  73. public static void main(String[] args) throws Exception{
  74. UploadServer uploadServer=new UploadServer();
  75. uploadServer.bind(20000);
  76. }
  77. }

最新文章

  1. webform(八)——LinQ简单增、删、改、查
  2. Java接口中的方法
  3. mac(linux) 上如何安装ant
  4. python写的分析mysql binlog日志工具
  5. Lambda应用设计模式
  6. JQuery基础教程:选择元素(上)
  7. 前端之JavaScript第一天学习(2)-JavaScript 使用
  8. 继承View绘制正方形且360旋转
  9. 【转】SqlLite .Net 4.0 System.IO.FileLoadException”类型的未经处理的异常出现在XXX
  10. CSS学习总结
  11. CENTOS6.6上搭建单实例ORACLE12C
  12. DLL文件修复
  13. springMVC_02hello案例
  14. Module not found: Error: Can't resolve 'XXX' in 'XXXX'
  15. php网站速度性能优化(转)
  16. 如何快速学好Shell脚本? 转
  17. 重载(overload)、覆盖(override)、隐藏(hide)的区别
  18. iOS将excel转plist
  19. P3159 [CQOI2012]交换棋子
  20. spring boot 2 内嵌Tomcat Stopping service [Tomcat]

热门文章

  1. Spring_事务
  2. ICP算法(迭代最近点)
  3. DirectX11笔记(二)--Direct3D初始化1之基本概念
  4. querySelector与getElementBy系列的区别
  5. python中几种单例模式的实现
  6. pytest fixture中scope试验,包含function、module、class、session、package
  7. 如何把一个普通的Eclipse项目改造成Eclipse Plugin项目
  8. qt获取本机用户名
  9. JavaScript--函数对象的属性caller与callee
  10. AtCoder Regular Contest 085 C HSI【概率论】