前言:
在linux 中 transferTo 方法就可以完成传输,在 windows 中依次调用transferTo最多能传8M文件,需要分段传文件,而且要注意传输起点位置
模拟服务端实验源码:
package com.dev.nio.TRANSFERTO;import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;/*** @author :* @date :2022/3/29 下午 2:24* @description :* @modyified By:*/
public class IOServer {public static void main(String[] args) throws Exception {//定义监听端口InetSocketAddress address = new InetSocketAddress(7001);//定义并打开一个通道ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();ServerSocket serverSocket = serverSocketChannel.socket();serverSocket.bind(address);//创建BUFFERByteBuffer byteBuffer = ByteBuffer.allocate(4096);while (true){SocketChannel socketChannel = serverSocketChannel.accept();int readcount = 0;while (readcount!=-1){try {readcount = socketChannel.read(byteBuffer);}catch (Exception e){
// e.printStackTrace();break;}byteBuffer.rewind();//倒带 position=1 mark 作废}}}}
模拟客户端实验源码:
package com.dev.nio.TRANSFERTO;import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;/*** @author : lei.yu* @date :2022/3/29 下午 2:24* @description : transferto 零拷贝客户端* @modyified By:*/
public class clentServer {public static void main(String[] args) throws Exception {String fileName="d:\\1m.7z";//需要传输的文件SocketChannel socketChannel = SocketChannel.open();InetSocketAddress address = new InetSocketAddress("localhost", 7001);socketChannel.connect(address);//得到一个文件channelFileChannel fileChannel = new FileInputStream(fileName).getChannel();//准备发送long startTime = System.currentTimeMillis();//在linux 中 transferTo 方法就可以完成传输//在 windows 中依次调用transferTo最多能传8M文件,需要分段传文件,而且要注意传输起点位置//transferTo 底层零拷贝long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);System.out.println("发送的总字节数="+transferCount+" 耗时:"+(System.currentTimeMillis()-startTime));//关闭socketChannel.close();fileChannel.close();}}
实验结果: