java NIO 网络编程

来源:互联网 发布:巴黎协定 知乎 编辑:程序博客网 时间:2024/05/03 07:59
IO(BIO) 和NIO 的区别:其本质就是阻塞和非阻塞的区别

 阻塞概念:应用程序在获取网络数据的时候,如果网络传输数据很慢,那么程序就一直等着,直到传输完毕为止。

 非阻塞概念:应用程序直接可以获取已经准备就绪好的数,无需等待。(会将数据放在缓存区,加载完后 会给客户端发送一个信号,客户端会读取数据)

IO为同步阻塞模式,NIO为同步非阻塞模式,NIO并没有实现异步,而JDK1.7以后AIO 支持异步。

同步时,应用程序会直接参与IO读写操作,并且我们的应用程序会直接阻塞到某一个方法上,直到数据准备就绪;或者采用轮询的策略实时检查数据的就绪状态,如果就绪则获取数据

异步时,则所有的IO读写操作交给操作系统处理,与我们的应用程序没有直接关系,我们程序不需要关系IO读写,当操作系统完成IO读写操作时,会给我们应用程序发送通知,我们的应用程序直接拿走数据即可。

同步说的事你的SERVER服务器端的执行方式

NIO的简单介绍:



Buffer 是一个对象,它包含一些要写入或者要读取的数据,在NIO中,所有的数据都是用缓冲区处理的,缓冲区实质是一个数组,通常它是一个字节数组

ByteBuffer

CharBuffer

ShortBuffer

IntBuffer

LongBuffer

我们来看下 Buffer的API:

public class TestBuffer {public static void main(String[] args) {// 1 基本操作//创建指定长度的缓冲区IntBuffer buf = IntBuffer.allocate(10);buf.put(13);// position位置:0 - > 1buf.put(21);// position位置:1 - > 2buf.put(35);// position位置:2 - > 3//把位置复位为0,也就是position位置:3 - > 0buf.flip();System.out.println("使用flip复位:" + buf);System.out.println("容量为: " + buf.capacity());//容量一旦初始化后不允许改变(warp方法包裹数组除外)System.out.println("限制为: " + buf.limit());//由于只装载了三个元素,所以可读取或者操作的元素为3 则limit=3System.out.println("获取下标为1的元素:" + buf.get(1));System.out.println("get(index)方法,position位置不改变:" + buf);buf.put(1, 4);System.out.println("put(index, change)方法,position位置不变:" + buf);;for (int i = 0; i < buf.limit(); i++) {//调用get方法会使其缓冲区位置(position)向后递增一位System.out.print(buf.get() + "\t");}System.out.println("buf对象遍历之后为: " + buf);

使用flip复位:java.nio.HeapIntBuffer[pos=0 lim=3 cap=10]容量为: 10限制为: 3获取下标为1的元素:21get(index)方法,position位置不改变:java.nio.HeapIntBuffer[pos=0 lim=3 cap=10]put(index, change)方法,position位置不变:java.nio.HeapIntBuffer[pos=0 lim=3 cap=10]13435buf对象遍历之后为: java.nio.HeapIntBuffer[pos=3 lim=3 cap=10]

// 2 wrap方法使用 //  wrap方法会包裹一个数组: 一般这种用法不会先初始化缓存对象的长度,因为没有意义,最后还会被wrap所包裹的数组覆盖掉。 //  并且wrap方法修改缓冲区对象的时候,数组本身也会跟着发生变化。                     int[] arr = new int[]{1,2,5};IntBuffer buf1 = IntBuffer.wrap(arr);System.out.println(buf1);IntBuffer buf2 = IntBuffer.wrap(arr, 0 , 2);//截取1-2下标//这样使用表示容量为数组arr的长度,但是可操作的元素只有实际进入缓存区的元素长度System.out.println(buf2);

java.nio.HeapIntBuffer[pos=0 lim=3 cap=3]java.nio.HeapIntBuffer[pos=0 lim=2 cap=3]

// 3 其他方法IntBuffer buf1 = IntBuffer.allocate(10);int[] arr = new int[]{1,2,5};buf1.put(arr);System.out.println(buf1);//一种复制方法IntBuffer buf3 = buf1.duplicate();System.out.println(buf3);//设置buf1的位置属性//buf1.position(0);buf1.flip();System.out.println(buf1);System.out.println("可读数据为:" + buf1.remaining());int[] arr2 = new int[buf1.remaining()];//将缓冲区数据放入arr2数组中去buf1.get(arr2);for(int i : arr2){System.out.print(Integer.toString(i) + ",");}

java.nio.HeapIntBuffer[pos=3 lim=10 cap=10]java.nio.HeapIntBuffer[pos=3 lim=10 cap=10]java.nio.HeapIntBuffer[pos=0 lim=3 cap=10]可读数据为:31,2,5,

通道Channel,它就像自来水管道一样,网络数据通过channle读取和写入,通道与流不同之处在于通道是双向的,而流只是一个方向上移动的,而通道可以读写二者同时进行,最关键的是可以与多路复用器结合起来,有多种的状态位,方便多路复用器去识别。

通道分为两类 : 一类是网络读写的 SelectableChannel 一类事用于文件操作的FileChannel 我们使用SocketChannel和ServerSocketChannel都是SelectableChannel的子类


多路复用器Selector 提供选择已经就绪的任务的能力。

简单地说 ,就是Selector会不断地轮询注册在其上的通道,如果某个通道发生了读写操作,这个通道就处于就绪状态,会被Selector轮询出来,通过SelectionKey可以获得取得就绪的Channel集合,从而进行后续的IO操作。

Selector线程就类似一个管理者Master 管理成千上万的管道

package bhz.nio;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.util.Iterator;public class Server implements Runnable{//1 多路复用器(管理所有的通道)private Selector seletor;//2 建立缓冲区private ByteBuffer readBuf = ByteBuffer.allocate(1024);//3 private ByteBuffer writeBuf = ByteBuffer.allocate(1024);public Server(int port){try {//1 打开路复用器this.seletor = Selector.open();//2 打开服务器通道ServerSocketChannel ssc = ServerSocketChannel.open();//3 设置服务器通道为非阻塞模式ssc.configureBlocking(false);//4 绑定地址ssc.bind(new InetSocketAddress(port));//5 把服务器通道注册到多路复用器上,并且监听阻塞事件ssc.register(this.seletor, SelectionKey.OP_ACCEPT);System.out.println("Server start, port :" + port);} catch (IOException e) {e.printStackTrace();}}@Overridepublic void run() {while(true){try {//1 必须要让多路复用器开始监听this.seletor.select();//2 返回多路复用器已经选择的结果集Iterator<SelectionKey> keys = this.seletor.selectedKeys().iterator();//3 进行遍历while(keys.hasNext()){//4 获取一个选择的元素SelectionKey key = keys.next();//5 直接从容器中移除就可以了keys.remove();//6 如果是有效的if(key.isValid()){//7 如果为阻塞状态if(key.isAcceptable()){this.accept(key);}//8 如果为可读状态if(key.isReadable()){this.read(key);}//9 写数据if(key.isWritable()){//this.write(key); //ssc}}}} catch (IOException e) {e.printStackTrace();}}}private void write(SelectionKey key){//ServerSocketChannel ssc =  (ServerSocketChannel) key.channel();//ssc.register(this.seletor, SelectionKey.OP_WRITE);}private void read(SelectionKey key) {try {//1 清空缓冲区旧的数据this.readBuf.clear();//2 获取之前注册的socket通道对象SocketChannel sc = (SocketChannel) key.channel();//3 读取数据int count = sc.read(this.readBuf);//4 如果没有数据if(count == -1){key.channel().close();key.cancel();return;}//5 有数据则进行读取 读取之前需要进行复位方法(把position 和limit进行复位)this.readBuf.flip();//6 根据缓冲区的数据长度创建相应大小的byte数组,接收缓冲区的数据byte[] bytes = new byte[this.readBuf.remaining()];//7 接收缓冲区数据this.readBuf.get(bytes);//8 打印结果String body = new String(bytes).trim();System.out.println("Server : " + body);// 9..可以写回给客户端数据 } catch (IOException e) {e.printStackTrace();}}private void accept(SelectionKey key) {try {//1 获取服务通道ServerSocketChannel ssc =  (ServerSocketChannel) key.channel();//2 执行阻塞方法SocketChannel sc = ssc.accept();//3 设置阻塞模式sc.configureBlocking(false);//4 注册到多路复用器上,并设置读取标识sc.register(this.seletor, SelectionKey.OP_READ);} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {new Thread(new Server(8765)).start();;}}


public class Client {//需要一个Selector public static void main(String[] args) {//创建连接的地址InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8765);//声明连接通道SocketChannel sc = null;//建立缓冲区ByteBuffer buf = ByteBuffer.allocate(1024);try {//打开通道sc = SocketChannel.open();//进行连接sc.connect(address);while(true){//定义一个字节数组,然后使用系统录入功能:byte[] bytes = new byte[1024];System.in.read(bytes);//把数据放到缓冲区中buf.put(bytes);//对缓冲区进行复位buf.flip();//写出数据sc.write(buf);//清空缓冲区数据buf.clear();}} catch (IOException e) {e.printStackTrace();} finally {if(sc != null){try {sc.close();} catch (IOException e) {e.printStackTrace();}}}}}
AIO


package bhz.aio;import java.net.InetSocketAddress;import java.nio.channels.AsynchronousChannelGroup;import java.nio.channels.AsynchronousServerSocketChannel;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Server {//线程池private ExecutorService executorService;//线程组private AsynchronousChannelGroup threadGroup;//服务器通道public AsynchronousServerSocketChannel assc;public Server(int port){try {//创建一个缓存池executorService = Executors.newCachedThreadPool();//创建线程组threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);//创建服务器通道assc = AsynchronousServerSocketChannel.open(threadGroup);//进行绑定assc.bind(new InetSocketAddress(port));System.out.println("server start , port : " + port);//进行阻塞assc.accept(this, new ServerCompletionHandler());//一直阻塞 不让服务器停止//Thread.sleep(Integer.MAX_VALUE);} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {Server server = new Server(8765);}}

package bhz.aio;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousSocketChannel;import java.nio.channels.CompletionHandler;import java.util.concurrent.ExecutionException;public class ServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Server> {@Overridepublic void completed(AsynchronousSocketChannel asc, Server attachment) {//当有下一个客户端接入的时候 直接调用Server的accept方法,这样反复执行下去,保证多个客户端都可以阻塞attachment.assc.accept(attachment, this);read(asc);}private void read(final AsynchronousSocketChannel asc) {//读取数据ByteBuffer buf = ByteBuffer.allocate(1024);asc.read(buf, buf, new CompletionHandler<Integer, ByteBuffer>() {@Overridepublic void completed(Integer resultSize, ByteBuffer attachment) {//进行读取之后,重置标识位attachment.flip();//获得读取的字节数System.out.println("Server -> " + "收到客户端的数据长度为:" + resultSize);//获取读取的数据String resultData = new String(attachment.array()).trim();System.out.println("Server -> " + "收到客户端的数据信息为:" + resultData);String response = "服务器响应, 收到了客户端发来的数据: " + resultData;write(asc, response);}@Overridepublic void failed(Throwable exc, ByteBuffer attachment) {exc.printStackTrace();}});}private void write(AsynchronousSocketChannel asc, String response) {try {ByteBuffer buf = ByteBuffer.allocate(1024);buf.put(response.getBytes());buf.flip();asc.write(buf).get();} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}@Overridepublic void failed(Throwable exc, Server attachment) {exc.printStackTrace();}}

package bhz.aio;import java.io.UnsupportedEncodingException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousSocketChannel;import java.util.concurrent.ExecutionException;public class Client implements Runnable{private AsynchronousSocketChannel asc ;public Client() throws Exception {asc = AsynchronousSocketChannel.open();}public void connect(){asc.connect(new InetSocketAddress("127.0.0.1", 8765));}public void write(String request){try {asc.write(ByteBuffer.wrap(request.getBytes())).get();read();} catch (Exception e) {e.printStackTrace();}}private void read() {ByteBuffer buf = ByteBuffer.allocate(1024);try {asc.read(buf).get();buf.flip();byte[] respByte = new byte[buf.remaining()];buf.get(respByte);System.out.println(new String(respByte,"utf-8").trim());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}}@Overridepublic void run() {while(true){}}public static void main(String[] args) throws Exception {Client c1 = new Client();c1.connect();Client c2 = new Client();c2.connect();Client c3 = new Client();c3.connect();new Thread(c1, "c1").start();new Thread(c2, "c2").start();new Thread(c3, "c3").start();Thread.sleep(1000);c1.write("c1 aaa");c2.write("c2 bbbb");c3.write("c3 ccccc");}}

0 0