5.NIO-网络编程-阻塞VS非阻塞

1.4、网络编程
1.4.1 阻塞VS非阻塞

阻塞:

  • ServerSocketChannel.accept() 阻塞到客户端连接
  • SocketChannel.read() 阻塞到客户端发送数据
//服务端
@Slf4j
public class SocketServerTest {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();

        ssc.bind(new InetSocketAddress(5888));

        ArrayList<SocketChannel> channels = new ArrayList<>();
        ByteBuffer buffer = ByteBuffer.allocate(16);
        while (true) {
            log.debug("connecting...");
            SocketChannel accept = ssc.accept();//阻塞方法,等待客户端连接。
            log.debug("connected...{}", accept);
            channels.add(accept);
            for (SocketChannel channel : channels) {
                log.debug("before read...{}", channel);
                channel.read(buffer);//阻塞方法,等待客户端发送数据
                buffer.flip();
                ByteBufferUtil.debugRead(buffer);
                buffer.clear();
                log.debug("after read...{}",channel);
            }
        }
    }
}

//客户端
public class Client {
    public static void main(String[] args) throws IOException {
        SocketChannel channel = SocketChannel.open();
        channel.connect(new InetSocketAddress("localhost", 5888));

        System.out.println("waiting...");
    }
}

非阻塞

客户端不便,服务只需要设置 configureBlocking(false)

@Slf4j
public class SocketServerNiotTest {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(5888));
        ssc.configureBlocking(false);//设置为非阻塞
        ArrayList<SocketChannel> channels = new ArrayList<>();
        ByteBuffer buffer = ByteBuffer.allocate(16);
        while (true) {
            SocketChannel accept = ssc.accept();//阻塞方法,等待客户端连接。
            if (accept != null) {
                log.debug("connected...{}", accept);
                accept.configureBlocking(false);//设置为非阻塞
                channels.add(accept);
            }

            for (SocketChannel channel : channels) {
                int read = channel.read(buffer);//阻塞方法,等待客户端发送数据
                if (read > 0) {
                    buffer.flip();
                    ByteBufferUtil.debugRead(buffer);
                    buffer.clear();
                    log.debug("after read...{}", channel);
                }
            }
        }
    }
}

问题:非阻塞模式,不管有没有客户端连接,不管客户端有没有发数据,服务店一直在循环,占用CPU资源

posted @   jpy  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2021-10-12 阿里云的这群疯子
点击右上角即可分享
微信分享提示