channel与流的区别:java
channel的主要实现:服务器
- FileChannel
- DatagramChannel:UDP读写
- SocketChannel:TCP读写
- ServerSocketChannel
支持scatter/gather(分散和汇集)dom
ByteBuffer header = ByteBuffer.allocate(128); ByteBuffer body = ByteBuffer.allocate(1024); ByteBuffer[] bufferArray = { header, body }; channel.read(bufferArray);
通道的建立:异步
除了FileChannel以外,都使用open建立。socket
FileChannel的建立以下:spa
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel();
Socket通道.net
分别对应java.net包中的Socket对象ServerSocket、Socket和DatagramSocket;Socket通道被实例化时,都会建立一个对等的Socket对象。code
Socket通道能够运行非阻塞模式而且是可选择的,非阻塞I/O与可选择性是紧密相连的,这也正是管理阻塞的API要在 SelectableChannel中定义的缘由。设置非阻塞很是简单,只要调用configureBlocking(false)方法便可。若是须要中 途更改阻塞模式,那么必须首先得到blockingLock()方法返回的对象的锁。对象
ServerSocketChannel实例:blog
1. 使用对等socket来bind监听。
2. 非阻塞状态下,accept在无链接时当即返回null
ByteBuffer buffer = ByteBuffer.wrap("Hello World".getBytes()); ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(12345)); ssc.configureBlocking(false); for (;;) { System.out.println("Waiting for connections"); SocketChannel sc = ssc.accept(); if (sc == null) TimeUnit.SECONDS.sleep(2000); else { System.out.println("Incoming connection from:" + sc.socket().getRemoteSocketAddress()); buffer.rewind(); sc.write(buffer); sc.close(); } }
非阻塞的read在无数据时当即返回0