java的NIO实现

单线程处理

package one;

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;

/**
 * nio单线程处理
 */
public class NioService1 {
    //通道管理器
    private Selector selector;
    public static void main(String[] args) throws IOException {
        NioService1 nioService3 = new NioService1();
        nioService3.initServer(8000);
        nioService3.listen();
    }

    /**
     * 获得一个ServerSocket通道,并对该通道做一些初始化的工作
     * @param port 绑定的端口号
     */
    public void initServer(int port) throws IOException {
        //获得一个ServerSocket通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //设置通道为非阻塞
        serverSocketChannel.configureBlocking(false);
        //将该通道对应的ServerSocket绑定到port端口
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        //获得一个通道管理器
        this.selector = Selector.open();
        //将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后
        //当该事件到达时,selector.select()会返回,如果该事件没有到达selector.select()会一直阻塞
        serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
    }

    /**
     * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
     */
    public void listen() throws IOException {
        System.out.println("服务器启动成功!");
        //轮询访问selector
        while (true){
            //当注册的事件到达时,方法返回,否则,该方法会一直阻塞
            selector.select();
            //获得selector中选中的项的迭代器,选中的项为注册的事件
            Iterator iterator =  this.selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = (SelectionKey) iterator.next();
                //删除已选的key,以防重复处理
                iterator.remove();

                handler(selectionKey);
            }
        }
    }

    /**
     * 处理请求
     * @param selectionKey
     */
    public void handler(SelectionKey selectionKey) throws IOException {
        if(selectionKey.isAcceptable()){
            //客户端请求连接事件
            handlerAccept(selectionKey);
        }else if(selectionKey.isReadable()){
            //获得了可读的事件
            handlerRead(selectionKey);
        }
    }

    /**
     * 处理连接请求
     * @param selectionKey
     */
    public void handlerAccept(SelectionKey selectionKey) throws IOException {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
        //获得和客户端连接的通道
        SocketChannel socketChannel = serverSocketChannel.accept();
        //设置成非阻塞
        socketChannel.configureBlocking(false);

        //在这里可以给客户端发送信息
        System.out.println("新的客户端连接");
        //在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限
        socketChannel.register(this.selector,SelectionKey.OP_READ);
    }

    /**
     * 处理读的事件
     * @param selectionKey
     */
    public void handlerRead(SelectionKey selectionKey) throws IOException {
        //服务器可读取消息:得到事件发生的Socket通道
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        //创建读取的缓冲区:缓冲小的话,一次获取不完所有的数据
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int intRead = socketChannel.read(byteBuffer);
        if(intRead > 0){
            byte[] data = byteBuffer.array();
            String msg = new String(data).trim();
            System.out.println("服务端收到信息:"+msg);

            //会写数据
            ByteBuffer outByteBuffer = ByteBuffer.wrap("好的".getBytes());
            //将消息会送给客户端
            socketChannel.write(outByteBuffer);
        }else{
            System.out.println("客户端关闭");
            selectionKey.cancel();
        }
    }
}

        该实例是BIO的简单实现,是一个线程+selector的实现,这种方式可以实现同时处理多个客户端请求的需求。在这个实例中我们可以知道,获得客户端请求的方法也是阻塞的,那为什么说这个实例就是NIO呢?这里需要注意,区别NIO和BIO的点,不是获得客户端请求时是否阻塞(当然,NIO可以设置成非阻塞或者被唤醒),而是在读取客户端数据时,是否可以立即返回,即:读取客户端数据时是否阻塞,BIO在读取客户端发送的数据时是阻塞的,NIO在读取客户端发送的数据时是非阻塞的。

        上面demo中存在一个问题,读取一个客户端发送的数据后,如果在处理这一个客户端的数据上用了1分钟,那么,在这1分钟内,该服务端无法进行其它任何事(不可以直接)


多线程处理

         单线程+selector的方式,可以解决同时处理多个客户端的请求,但是存在如上所述的问题,对于解决的方法,相信大家也都知道,就是采用多线程的方式。

/**
     * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
     */
    public void listen() throws IOException {
        System.out.println("服务器启动成功!");
        //轮询访问selector
        while (true){
            //当注册的事件到达时,方法返回,否则,该方法会一直阻塞
            selector.select();//当发现客户端还没有处理时,就不会阻塞
            //获得selector中选中的项的迭代器,选中的项为注册的事件
            Iterator iterator =  this.selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = (SelectionKey) iterator.next();
                //删除已选的key,以防重复处理
                iterator.remove();

                //业务处理
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            handler(selectionKey);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }
        使用上面的这种方式很可能会抛出异常,因为当第一次将A客户端请求交给业务线程处理后,代码再次循环到selector.select()时,发现A客户端请求还存在,此时,会再次将A请求发给业务线程处理,此时可能存在的情况是,可能进行了多次的业务处理,可能上次业务处理完成了,本次在获取A客户端时出现空异常。

        如果实现NIO的多线程处理呢,采用的思路是使用多个selector,一个selector仅监听客户端链接,业务处理是多个线程,每个线程一个selector。当监听到客户端链接后,就把客户端交给一个业务线程的selector。


BIO和NIO

        我们可以做一个比喻,我们把我们的服务器端系统作为餐厅,把餐厅的大门作为监听的端口,客人为socket客户端,一个服务员为一个线程。

       BIO的多线程实现图,大门有一个服务,里面是一个客人一个服务员。

        BIO的单线程实现图,该餐厅就一个服务员,该服务员在大门迎接客人,又在里面服务客人。


        BIO的多线程实现图,门口一个服务员,里面一个服务员负责一个区,该去内的所有客人都给该服务员服务。


总结

        通过上面的图,我们可以知道,java的NIO的多线程是较好的一种服务方式,netty就是采用的这种方式,通过对java的nio进行相应的代码封装,而实现的一种NIO框架。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值