Java传统IO和网络编程的一段代码
DMA : direct memory access 直接内存拷贝( 不使用CPU )
server
package com.dance.netty.nio.demo.zerocopy;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class ZeroCopyServer {
public static void main(String[] args) throws Exception {
InetSocketAddress inetSocketAddress = new InetSocketAddress(7001);
ServerSocketChannel open = ServerSocketChannel.open();
open.socket().bind(inetSocketAddress);
for (;;){
SocketChannel accept = open.accept();
int countSize = 0;
ByteBuffer allocate = ByteBuffer.allocate(4096);
while (-1 != countSize){
countSize = accept.read(allocate);
allocate.rewind(); // 倒置 position=0 Mark 作废
}
}
}
}
client
package com.dance.netty.nio.demo.zerocopy;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.time.Duration;
import java.time.Instant;
public class ZeroCopyClient {
public static void main(String[] args) throws Exception {
SocketChannel open = SocketChannel.open();
boolean connect = open.connect(new InetSocketAddress(7001));
// 获取文件Channel
File file = new File("src/main/resources/01.jpeg");
FileChannel channel = new FileInputStream(file).getChannel();
Instant startTime = Instant.now();
/*
* 在Linux下,一个transferTo方法就可以传输完成
* 在Windows下,调用一次transferTo 只能传输8M,就需要分段传输文件,而且要记录传输时的位置
* transferTo 底层使用零拷贝
*/
long l = channel.transferTo(0, channel.size(), open);
System.out.println(l);
Instant endTime = Instant.now();
System.out.println("用时:" + Duration.between(startTime,endTime).toMillis() + "ms");
channel.close();
}
}
6806
用时:3ms
https://blog.csdn.net/weixin_42096901/article/details/103017044
我感觉写的很不错
举例说明
NIO完结撒花花