NIO的非阻塞式实现

首先解释一下阻塞和非阻塞
对于传统的BIO,线程在同一时间只能等待数据的发送和接收,在此期间不能做其他的事
用图来表示
在这里插入图片描述
所以对于这种io,我们应该使用多线程的方式完成io通信
在这里插入图片描述
多线程虽然能完成同时接收和发送,但是本质上也是多个阻塞的单线程,多个线程中某个陷入阻塞,该线程还是不能做其他的事,造成资源的浪费。

在这里插入图片描述
NIO非阻塞模式,将每一个用于传输数据的通道都注册到选择器上,选择器监控通道的io状况(读,写,连接,接收数据),当某个通道上某个请求的事件完全就绪的时候,选择器才会将该任务分配给服务端的一个或多个线程,其他情况服务器的线程可以做其他事情。

nio非阻塞模式代码实现:
客户端

    //客户端
    @Test
    public void TestClient(){
        SocketChannel client=null;
        ByteBuffer buffer=null;
        try {
            //获取socket连接
            client = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
            //切换非阻塞状态
            client.configureBlocking(false);
            //指定缓冲区
            buffer = ByteBuffer.allocate(1024);
            //从控制台读入数据,发送数据到服务端
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                buffer.put(scanner.next().getBytes());
                //切换成读模式
                buffer.flip();
                client.write(buffer);
                buffer.clear();
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (client!=null){
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } 

服务端

@Test
    public void TestServer() throws IOException {
        ServerSocketChannel server = ServerSocketChannel.open();
        //1.切换非阻塞模式
        server.configureBlocking(false);
        //2.绑定
        server.bind(new InetSocketAddress("127.0.0.1",9898));
        //3.获取选择器
        Selector selector = Selector.open();
        //4.将服务注册到选择器上,第二个参数式选择键selectionkey表示,有四个常量
        // (1)selectionkey.OP_READ 读操作    (2)selectionkey.OP_WRITE 写操作     (3)selectionkey.OP_CONNECT 连接操作     (4)selectionkey.OP_ACCEPT 接收操作
        server.register(selector, SelectionKey.OP_ACCEPT);  //将读事件注册到选择器上
        //5.轮询式的获取选择器上已经准备就绪的事件
        while (selector.select()>0){
            //6.获取当前选择器中所有注册的“选择键”
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                //7.判断什么事件准备就绪
                if (key.isAcceptable()){
                    //8.如果是接收就绪,采取动作
                    SocketChannel accept = server.accept();
                    //9.切换非阻塞状态
                    accept.configureBlocking(false);
                    //10.将读事件注册到selector上
                    accept.register(selector,SelectionKey.OP_READ);
                }else if (key.isReadable()){
                    //11.获取当前选择器上“读状态”的通道
                    SocketChannel channel =(SocketChannel) key.channel();
                    //12.读取数据
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len=0;
                    while ((len=channel.read(buffer))>0){
                        buffer.flip();
                        String s = new String(buffer.array(), 0, len);
                        System.out.println(s);
                        buffer.clear();
                    }
                }
                //执行完任务之后就要取消选择键  因为将acceptor也
                iterator.remove();
            }
        }
    }
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
NIO(Non-blocking I/O)是Java中的一种I/O模型,它可以实现非阻塞的I/O操作。使用NIO实现文件批量上传可以提高文件上传的效率,下面是一个简单的实现过程: 1. 创建ServerSocketChannel对象,并且绑定一个端口号。 2. 创建Selector对象,并且将ServerSocketChannel注册到Selector中,同时设置为非阻塞。 3. 在循环中,使用Selector的select()方法来监听事件。当有事件发生时,使用selectedKeys()方法来获取事件集合。 4. 对于每一个事件,判断其类型。如果是连接事件,就创建一个SocketChannel对象,并将其注册到Selector中,同时设置为非阻塞。如果是读事件,就从SocketChannel中读取数据,并将其保存到文件中。 5. 在客户端中,创建SocketChannel对象,并连接到服务器。然后将文件分成多个块,每个块都创建一个ByteBuffer对象,并将其写入SocketChannel中。 下面是一个简单的NIO文件上传的示例代码: ``` public class NIOFileUploadServer { private static final int PORT = 8888; private static final int BUFFER_SIZE = 1024; private static final String UPLOAD_DIR = "D:\\upload\\"; public static void main(String[] args) throws IOException { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(PORT)); serverSocketChannel.configureBlocking(false); Selector selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { int readyChannels = selector.select(); if (readyChannels == 0) { continue; } Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); if (key.isAcceptable()) { ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { SocketChannel socketChannel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); FileChannel fileChannel = new FileOutputStream(UPLOAD_DIR + "test.txt").getChannel(); while (socketChannel.read(buffer) > 0) { buffer.flip(); fileChannel.write(buffer); buffer.clear(); } fileChannel.close(); socketChannel.close(); } } } } } ``` 客户端代码: ``` public class NIOFileUploadClient { private static final String SERVER_IP = "localhost"; private static final int SERVER_PORT = 8888; private static final int BUFFER_SIZE = 1024; private static final String FILE_PATH = "D:\\test.txt"; public static void main(String[] args) throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT)); socketChannel.configureBlocking(false); FileChannel fileChannel = new FileInputStream(FILE_PATH).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); while (fileChannel.read(buffer) > 0) { buffer.flip(); socketChannel.write(buffer); buffer.clear(); } fileChannel.close(); socketChannel.close(); } } ``` 需要注意的是,上述代码仅为示例,实际使用时需要添加必要的异常处理和错误处理。同时,文件上传时需要对文件进行分块,以免一次性上传过大的文件导致服务器负载过高。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值