本次是利用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. }

Netty进行文件传输的更多相关文章

  1. netty 文件传输

    FileServer package com.zhaowb.netty.ch13_1; import io.netty.bootstrap.ServerBootstrap; import io.net ...

  2. RPC基于http协议通过netty支持文件上传下载

    本人在中间件研发组(主要开发RPC),近期遇到一个需求:RPC基于http协议通过netty支持文件上传下载 经过一系列的资料查找学习,终于实现了该功能 通过netty实现文件上传下载,主要在编解码时 ...

  3. Linux主机上实现树莓派的交叉编译及文件传输,远程登陆

    0.环境 Linux主机OS:Ubuntu14.04 64位,运行在wmware workstation 10虚拟机 树莓派版本:raspberry pi 2 B型. 树莓派OS:官网下的的raspb ...

  4. putty提供的两个文件传输工具PSCP、PSFTP详细介绍

    用 SSH 来传输文件 PuTTY 提供了两个文件传输工具 PSCP (PuTTY Secure Copy client) PSFTP (PuTTY SFTP client) PSCP 通过 SSH ...

  5. c# 局域网文件传输实例

    一个基于c#的点对点局域网文件传输小案例,运行效果截图 //界面窗体 using System;using System.Collections.Generic;using System.Compon ...

  6. 使用 zssh 进行 Zmodem 文件传输

    Zmodem 最早是设计用来在串行连接(uart.rs232.rs485)上进行数据传输的,比如,在 minicom 下,我们就可以方便的用 Zmodem (说 sz .rz 可能大家更熟悉)传输文件 ...

  7. 在windows 与Linux间实现文件传输(C++&C实现)

    要实现windows与linux间的文件传输,可以通过socket网络编程来实现. 这次要实现的功能与<Windows下通过socket进行字符串和文件传输>中实现的功能相同,即客户端首先 ...

  8. Windows下通过socket进行字符串和文件传输

    今天在windows平台下,通过socket实现了简单的文件传输.通过实现这一功能,了解基本的windows网络编程和相关函数的使用方法. 在windows平台上进行网络编程,首先都需要调用函数WSA ...

  9. Linux下几种文件传输命令 sz rz sftp scp

    Linux下几种文件传输命令 sz rz sftp scp 最近在部署系统时接触了一些文件传输命令,分别做一下简单记录: 1.sftp Secure Ftp 是一个基于SSH安全协议的文件传输管理工具 ...

随机推荐

  1. Linux硬链接和软连接

    硬链接(hard link): A是B的硬链接(A和B都是文件名),则A的目录项中的inode节点号与B的目录项中的inode节点号相同,即一个inode节点对应两个不同的文件名,两个文件名指向同一个 ...

  2. Nginx 对访问量的控制

    目的 了解 Nginx 的 ngx_http_limit_conn_module 和 ngx_http_limit_req_module 模块,对请求访问量进行控制. Nginx 模块化 nginx ...

  3. vue-waterfall2 基于Vue.js 瀑布流组件

    vue-waterfall2 1.宽度自适应,数据绑定特效(适用于上拉加载更多) 2.自定义程度高 3.使用极为简便,适用于PC/移动端 4.提供resize(强制刷新布局-适用于下拉刷新)/mix( ...

  4. 【水滴石穿】React-Redux-Demo

    这个项目没有使用什么组件,可以理解就是个redux项目 项目地址为:https://github.com/HuPingKang/React-Redux-Demo 先看效果图 点击颜色字体颜色改变,以及 ...

  5. openssl生成SSL证书的流程 - moonhillcity的博客 - CSDN博客

    1.安装openssl 之后在/usr/lib/ssl目录下(ubuntu系统,用whereis查下ssl目录即可)下找到openssl.cnf,拷贝到工作目录下. 2.工作目录下新建demoCA文件 ...

  6. 使用HashMap编写一程序实现存储某班级学生信息

    1. 使用HashMap编写一程序实现存储某班级学生信息,要求在屏幕上打印如下列表 学号   姓名   性别   年龄 001    张三   男      23 002    李四   男      ...

  7. nginx与apache

    参考链接:https://www.cnblogs.com/changning0822/p/7844004.html

  8. Mysql里查询字段为Json格式的数据模糊查询以及分页方法

    public void datagrid(CustomFormEntity customForm,HttpServletRequest request, HttpServletResponse res ...

  9. 远程安装App到手机

    注意: 必须是手机和电脑网络连通正常 1. 手机端安装终端模拟器. 2. 打开终端模拟器执行下面命令(也可以在adb shell中执行): su setprop service.adb.tcp.por ...

  10. win2003开启ftp

    首先你要添加IIS,然后才可以启动配置FTP,步骤如下: 1.控制面板→添加或删除程序→添加/删除windows组件: 2.在弹出的windows组件向导窗口中,选择并勾选“应用程序服务器”,然后点击 ...