NIO 阻塞与非阻塞 SocketChannel、Selector、DatagramChannel

使用NIO完成网络通信三个核心:
1.通道(Channel):负责连接
2.缓冲区(Buffer):负责数据存取
3.选择器(Selector):是SelectableChannel的多路复用器,用于监控SelectableChannel的I/O状况
在这里插入图片描述

FileChannel不能切换成非阻塞模式

阻塞式:

	@Test
    public void bioSocketClient() {
        SocketChannel sChannel = null;
        FileChannel fChannel = null;
        try {
            sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 7478));
            fChannel = FileChannel.open(Paths.get("E:", "a.jpg"), StandardOpenOption.READ);

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            while(fChannel.read(byteBuffer) != -1) {
                byteBuffer.flip();
                sChannel.write(byteBuffer);
                byteBuffer.clear();
            }

            sChannel.shutdownOutput(); //告诉服务端发送完了,否则服务端会一直阻塞等待

            int len = 0;
            while((len = sChannel.read(byteBuffer)) != -1) {
                System.out.println(new String(byteBuffer.array(), 0, len));
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fChannel.close();
                sChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Test
    public void bioSocketServer() {
        ServerSocketChannel ssChannel = null;
        FileChannel fChannel = null;
        try {
            //获取通道
            ssChannel = ServerSocketChannel.open();
            //绑定连接
            ssChannel.bind(new InetSocketAddress(7478));
            fChannel = FileChannel.open(Paths.get("E:", "s.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
            //获取客户端连接的通道
            SocketChannel sChannel = ssChannel.accept();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            while(sChannel.read(byteBuffer) != -1) {
                byteBuffer.flip();
                fChannel.write(byteBuffer);
                byteBuffer.clear();
            }

            //发送反馈给客户端
            byteBuffer.put("服务端接受成功".getBytes());
            byteBuffer.flip();
            sChannel.write(byteBuffer);

            sChannel.shutdownOutput(); //告诉客户端发送完了,否则客户端会一直阻塞等待


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fChannel.close();
                ssChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

TCP传输模式中,调用Socket的shutdownInput()和shutdownOutput()都做了些什么?

非阻塞式:
通道注册到选择器上

	@Test
    public void bioSocketClient() {
        SocketChannel sChannel = null;
        FileChannel fChannel = null;
        try {
            //获取通道
            sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 7478));
            //切换非阻塞模式
            sChannel.configureBlocking(false);

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String msg = scanner.next();
                byteBuffer.put((LocalDateTime.now().toString() + "\n" + msg).getBytes());
                byteBuffer.flip();
                sChannel.write(byteBuffer);
                byteBuffer.clear();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                sChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void bioSocketServer() {
        ServerSocketChannel ssChannel = null;
        FileChannel fChannel = null;
        try {
            //获取通道
            ssChannel = ServerSocketChannel.open();
            ssChannel.configureBlocking(false);
            //绑定连接
            ssChannel.bind(new InetSocketAddress(7478));
            //将通道注册到选择器上
            Selector selector = Selector.open();
            //并指定监听事件
            ssChannel.register(selector, SelectionKey.OP_ACCEPT);
            while (selector.select() > 0) {

                //轮询获取选择器上已经就绪的事件
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();
                    if (selectionKey.isAcceptable()) {
                        //若“接收就绪”,获取客户端连接
                        SocketChannel sChannel = ssChannel.accept();
                        //切换非阻塞式
                        sChannel.configureBlocking(false);
                        //将该通道注册到选择器上
                        sChannel.register(selector, SelectionKey.OP_READ);
                    } else if (selectionKey.isReadable()) {
                        //获取当前选择器上读就绪状态的通道
                        SocketChannel sChannel = (SocketChannel) selectionKey.channel();
                        //读取数据
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int len = 0;
                        while ((len = sChannel.read(byteBuffer)) > 0) {
                            byteBuffer.flip();
                            System.out.println(new String(byteBuffer.array(), 0, len));
                            byteBuffer.clear();
                        }
                    }
                    //取消selectionKey
                    it.remove();
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ssChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

udp

	@Test
    public void datagramChannelSend() {
        DatagramChannel openChannel = null;
        try {
            openChannel = DatagramChannel.open();

            openChannel.configureBlocking(false);

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            Scanner scanner = new Scanner(System.in);

            while (scanner.hasNext()) {
                String msg = scanner.next();
                byteBuffer.put((LocalDateTime.now() + "\n" + msg).getBytes());
                byteBuffer.flip();
                openChannel.send(byteBuffer, new InetSocketAddress("127.0.0.1", 7575));
                byteBuffer.clear();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                openChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Test
    public void datagramChannelreceive() {
        DatagramChannel openChannel = null;
        try {
            openChannel = DatagramChannel.open();

            openChannel.configureBlocking(false);

            openChannel.bind(new InetSocketAddress(7575));

            Selector selector = Selector.open();
            openChannel.register(selector, SelectionKey.OP_READ);

            while(selector.select() > 0) {
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();
                    if(selectionKey.isReadable()) {
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        openChannel.receive(byteBuffer);
                        byteBuffer.flip();
                        System.out.println(new String(byteBuffer.array(), 0, byteBuffer.limit()));
                        byteBuffer.clear();
                    }
                }
                it.remove();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                openChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值