JAVA NIO 通道 channel

1.作用:在缓冲区与实体之间传输数据的管道

2.通道类型

文件通道和套接字通道

3.创建通道

socket通道

 

SocketChannel sc1 = SocketChannel.open();
sc1.connect(new InetSocketAddress(hostname, port));
SocketChannel sc2 = SocketChannel.open(new InetSocketAddress(hostname, port));
SocketChannel sc3 = SocketChannel.open();
sc3.bind(new InetSocketAddress(hostname, port))

 File通道

RandomAccessFile raf = new RandomAccessFile(file, mode);
FileChannel fc1 = raf.getChannel();
FileInputStream in = new FileInputStream(file);
FileChannel fc2 = in.getChannel();
FileOutputStream out = new FileOutputStream(file)
FileChannel fc3 = out.getChannel();

 

 4.channel通道会连接一个特定的IO服务且性能会受到其连接的IO服务的影响

 

5.矢量IO Scatter Gather

Gather: 将多个缓冲区的数据顺序抽取

Scatter: 将数据按顺序散布到多个缓冲区

GatheringByteChannel

ScatteringByteChannel

ByteBuffer buf1 = ByteBuffer.allocate(15000);
ByteBuffer buf2 = ByteBuffer.allocate(15000);
ByteBuffer[] pool = {buf1, buf2};
File file = new File("/data/2013101112.png");
FileInputStream in = new FileInputStream(file);
ScatteringByteChannel channel = in.getChannel();
channel.close();
channel.read(pool);
	
System.out.println(buf1.position());
System.out.println(buf2.position());

buf1.flip();
buf2.flip();
File fileBak = new File("/data/2013101112_bak.png");
if(!fileBak.exists()) {
    fileBak.createNewFile();
}
FileOutputStream out = new FileOutputStream(fileBak);
GatheringByteChannel gChannel = out.getChannel();
gChannel.write(pool);
gChannel.close();
out.close();

 

 6.FileChannel

总是阻塞的,文件IO的强大在于异步IO,FileChannel属于线程安全的

掌握锁的使用和概念 lock tryLOck

掌握内存映射文件 map

 

 7.Socket通道

SocketChannel ServerSocketChannel DatagramChannel

非阻塞式

ServerSocketChannel sc = ServerSocketChannel.open();
		sc.socket().bind(new InetSocketAddress("127.0.0.1", 9069));
		sc.configureBlocking(false);
		ByteBuffer buf = ByteBuffer.wrap("hello channel".getBytes());
		
		while(true) {
			SocketChannel channel = sc.accept();
			if(channel == null) {
				Thread.sleep(1000);
			} else {
				System.out.println("FROM " + channel.getRemoteAddress());
				buf.rewind();
				channel.write(buf);
				channel.close();
			}
		}

 

ByteBuffer buf = ByteBuffer.allocate(2048);
		System.out.println(buf.capacity());
		System.out.println(buf.limit());
		SocketChannel sc = SocketChannel.open();
		sc.configureBlocking(false);
		sc.connect(new InetSocketAddress("127.0.0.1", 9069));
		sc.configureBlocking(false);
		while (!sc.finishConnect());
		// sc.read(buf);
		sc.close();
		System.out.println(buf.limit());
		buf.flip();
		while (buf.hasRemaining()) {
			System.out.println();
		}

 

 

你可能感兴趣的:(nio,channel)