JavaNIO中的內存映射io
阿新 • • 發佈:2019-01-11
get() num generate pmod 開始 讀寫 con 應用程序 copy
客戶端代碼:
package cc.client; import java.io.*; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.*; public class ClientOper { public static void main(String[] args) throws IOException { File file=new File("test.txt"); RandomAccessFile raf=new RandomAccessFile(file, "rw"); FileChannel fileChannel=raf.getChannel(); //內存映射,將內核緩存區的內存進行映射,應用程序可以像操作用戶緩存區一樣向內核緩存區讀寫數據。 MappedByteBuffer mbb=fileChannel.map(FileChannel.MapMode.READ_WRITE, 0,1024 ); //寫入數據 for(int i=0;i<1024;i++) mbb.put((byte)‘c‘); raf.close();/* SocketChannel sChannel = SocketChannel.open(); sChannel.configureBlocking(false); //建立連接 sChannel.connect(new InetSocketAddress("127.0.0.1", 80)); while (!sChannel.finishConnect()) { System.out.println("等待非阻塞連接建立...."); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } //這時依舊需要CPU將內核緩沖區的內容拷貝到網絡緩沖區 while(mbb.hasRemaining()) { sChannel.write(mbb); } fileChannel.close(); raf.close();*/ //測試消息成功寫入了test文件 /*FileInputStream fs=new FileInputStream(file); byte[] bytes=new byte[1024]; StringBuilder stringb=new StringBuilder(); //開始讀消息 int length; while((length=fs.read(bytes))!=-1) { stringb.append(new String(bytes,0,length)); } System.out.println(stringb); fs.close();*/ } }
服務端代碼:
public class ServerOper { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.bind(new InetSocketAddress(80)); serverSocket.configureBlocking(false); SocketChannel socketChannel = null; while(socketChannel==null) { socketChannel=serverSocket.accept(); } ByteBuffer byteBuffer=ByteBuffer.allocate(1024); int numByetsRead; while((numByetsRead = socketChannel.read(byteBuffer)) != -1) { if (numByetsRead == 0) { // 如果沒有數據,則稍微等待一下 try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } continue; } // 轉到最開始 byteBuffer.flip(); while (byteBuffer.remaining() > 0) { System.out.print((char) byteBuffer.get()); } } socketChannel.close(); serverSocket.close(); } }
參考:JavaNIO和零拷貝(Zero Copy)
https://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ314_029.htm
JavaNIO中的內存映射io