一、概念
1、零拷贝从操作系统角度看,是没有cpu拷贝,既CPU拷贝数据很少可以忽略。
二、代码
package com.hao.demo.netty;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
/**
* @author haoxiansheng
* @date 2020-05-19
*/
public class NewIOClient {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("loacllhost", 7001));
String fileName = "hao.zip";
// 得到一个FileChannel
FileChannel fileChannel = new FileInputStream(fileName).getChannel();
// 准备发送
long startTime = System.currentTimeMillis();
// 在linux 下一个transferTo 方法就可以完成传输
// 在windoes 下一次调用transferTo 只能发送8m,就需要分段传输文件,而且要注意传输的额位置 自己计算
// 做个算发transferTo(position, fileChannel.size(), socketChannel)
// transferTo 底层使用倒零拷贝 可以区里面看一下他方法的描述
long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
System.out.println("发送总的字节数 = " + transferCount + "耗时" + (System.currentTimeMillis() - startTime));
// 关闭
fileChannel.close();
}
}
package com.hao.demo.netty;
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 haoxiansheng
* @date 2020-05-19
*/
// 服务器端
public class NewIOServer {
public static void main(String[] args) throws IOException {
InetSocketAddress address = new InetSocketAddress(7001);
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
ServerSocket serverSocket = serverSocketChannel.socket();
serverSocket.bind(address);
// 创建buffer
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (true) {
SocketChannel socketChannel = serverSocketChannel.accept(); // 监听
int readCount = 0;
while (readCount != -1) {
try{
readCount = socketChannel.read(byteBuffer);
} catch (Exception e) {
break;
}
//
byteBuffer.rewind(); // 倒袋 position = 0 mark 作废
}
}
}
}