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资源
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
2021-10-12 阿里云的这群疯子