本文共 3378 字,大约阅读时间需要 11 分钟。
package com.atguigu.nio.zerocopy;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;public class NewIOServer { public static void main(String[] args) throws Exception { InetSocketAddress address = new InetSocketAddress(7002); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); ServerSocket serverSocket = serverSocketChannel.socket(); serverSocket.bind(address); ByteBuffer byteBuffer = ByteBuffer.allocate(4096); while (true) { SocketChannel socketChannel = serverSocketChannel.accept(); int readCount = 0; while (-1 != readCount) { try { readCount = socketChannel.read(byteBuffer); } catch (Exception e) { break; } byteBuffer.rewind(); } } }} package com.atguigu.nio.zerocopy;import java.io.FileInputStream;import java.net.InetSocketAddress;import java.nio.channels.FileChannel;import java.nio.channels.SocketChannel;public class NewIOClient { public static void main(String[] args) throws Exception { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost", 7002)); String filename = "./test.avi"; FileChannel fileChannel = new FileInputStream(filename).getChannel(); long startTime = System.currentTimeMillis(); long totalSize = fileChannel.size(); long max_pkg = 8 * 1024 * 1024; long cur_pos = 0; long transSize = 0; while (totalSize > max_pkg) { long tmp = fileChannel.transferTo(cur_pos, max_pkg, socketChannel); totalSize -= tmp; cur_pos += tmp; transSize += tmp; } if (totalSize > 0) { long tmp = fileChannel.transferTo(cur_pos, totalSize, socketChannel); transSize += tmp; } System.out.println("Total bytes transferred: " + transSize + " Elapsed time: " + (System.currentTimeMillis() - startTime)); fileChannel.close(); }} 7002 using InetSocketAddress.ByteBuffer of size 4096 to read data from connected clients.7002.FileInputStream and converts it to a FileChannel for NIO operations.This implementation demonstrates the practical application of NIO's zero copy mechanism for high-performance file transfer scenarios.
转载地址:http://cqaa.baihongyu.com/