Netty01. BIO与NIO
文章目录
BIO:同步阻塞
NIO:同步非阻塞(多路复用)
同步:
阻塞事件的I/O,读或写,同时我们不能做任何处理的事情;
阻塞:
在等待缓冲区数据的时候准备好了之后才能处理其他事情,否则一直在那等待
非阻塞:
在我们在访问数据缓冲区的时候,如果数据没有准备好,直接返回不会等待在数据准备好的话也直接反馈结果
我们一般用Socket接收数据的时候,socket.accept()一直处与阻塞的状态,等待消息接收才能处理;-->BIO
NIO案例:并且多路复用
package com.ldp.nio;
import com.sun.org.apache.bcel.internal.generic.Select;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
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;
import java.util.Set;
public class NIOServerDemo {
//端口
private int port \= 8080;
//轮询器
private Selector selector;
//缓冲区
private ByteBuffer buffer \= ByteBuffer.allocate(1024);
//进行初始化操作
private NIOServerDemo(int port){
try {
ServerSocketChannel socketChannel = ServerSocketChannel.open();
//告诉地址 端口 默认为localhost
//this(InetAddress.anyLocalAddress(), port); socketChannel.bind(new InetSocketAddress(port));
//默认为BIO false 改为NIO
socketChannel.configureBlocking(false);
SocketChannel accept = socketChannel.accept();
//准备接收数据
selector \= Selector.open();
//接收传过来的数据
socketChannel.register(selector, SelectionKey.OP\_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
public void listen(){
System.out.println("listen on "+this.port+".");
try {
//进行轮询接收数据处理
while (true){
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
//不断的尽心循环,每一个一个状态进行处理.
Iterator<SelectionKey> iter = keys.iterator();
while (iter.hasNext()){
SelectionKey key = iter.next();
//一个key代表一个状态,在处理完之后,进行移除
process(key);
iter.remove();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
//具体办业务的方法,坐班柜员
//每一次轮询就是调用一次process方法,而每一次调用,只能干一件事
//在同一时间点,只能干一件事
// I/o多路复用 多个处理
private void process(SelectionKey key) throws IOException {
//一个key代表一个状态进行处理
if (key.isAcceptable()){
// System.out.println("千万21");
ServerSocketChannel channel =(ServerSocketChannel) key.channel();
//数据有没有准备好,都需要返回一个状态
//进行阻塞
SocketChannel accept = channel.accept();
//false将BIO->NIO
accept.configureBlocking(false);
//当数据准备就绪的时候,将状态改为可读
key = accept.register(selector,SelectionKey.OP\_READ);
}
else if(key.isReadable()){
//key.channel 从多路复用器中拿到客户端的引用
SocketChannel channel = (SocketChannel)key.channel();
int len = channel.read(buffer);
if(len > 0){
buffer.flip();
String content = new String(buffer.array(),0,len);
key = channel.register(selector,SelectionKey.OP\_WRITE);
//在key上携带一个附件,一会再写出去
key.attach(content);
System.out.println("读取内容:" \+ content);
}
}
else if(key.isWritable()){
SocketChannel channel = (SocketChannel)key.channel();
String content = (String)key.attachment();
channel.write(ByteBuffer.wrap(("输出:" \+ content).getBytes()));
channel.close();
}
}
public static void main(String\[\] args) {
new NIOServerDemo(8080).listen();
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论