欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

netty-阻塞模式,非阻塞模式

发布时间:2025/6/15 编程问答 26 豆豆
生活随笔 收集整理的这篇文章主要介绍了 netty-阻塞模式,非阻塞模式 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

以下方法为阻塞模式(单线程)
只能干一件事。

import lombok.extern.slf4j.Slf4j;import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.List;import static com.netty.c1.ByteBufferUtil.debugRead;@Slf4j(topic = "c.Server") public class Server {public static void main(String[] args) throws IOException {ByteBuffer buffer = ByteBuffer.allocate(16);// 创建服务器ServerSocketChannel ssc = ServerSocketChannel.open();// 绑定监听端口ssc.bind(new InetSocketAddress(8080));List<SocketChannel> channels = new ArrayList<>();while(true) {log.debug("connection...");// 建立与客户端的连接SocketChannel sc = ssc.accept(); // 阻塞方法,线程停止运行log.debug("connected...{}",sc);channels.add(sc);// 接受客户端发送的数据for (SocketChannel channel : channels) {log.debug("before read...{}",channel);channel.read(buffer); // 阻塞方法,线程停止运行buffer.flip();debugRead(buffer);buffer.clear();log.debug("after read...{}",channel);}}} }

以下方法为非阻塞模式(单线程)

import lombok.extern.slf4j.Slf4j;import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.List;import static com.netty.c1.ByteBufferUtil.debugRead;@Slf4j(topic = "c.Server") public class Server {public static void main(String[] args) throws IOException {ByteBuffer buffer = ByteBuffer.allocate(16);// 创建服务器ServerSocketChannel ssc = ServerSocketChannel.open();// 非阻塞模式ssc.configureBlocking(false);// 绑定监听端口ssc.bind(new InetSocketAddress(8080));List<SocketChannel> channels = new ArrayList<>();// 有一个缺点:没有连接请求时,也会不断循环。// 没有数据可读时,也会不断循环。while(true) {//log.debug("connection...");// 建立与客户端的连接SocketChannel sc = ssc.accept(); // 非阻塞,线程还会继续运行。如果没有建立连接,sc是nullif(sc != null){log.debug("connected...{}",sc);sc.configureBlocking(false);channels.add(sc);}// 接受客户端发送的数据for (SocketChannel channel : channels) {//log.debug("before read...{}",channel);int read = channel.read(buffer); // 非阻塞,线程仍然继续运行。如果没有读到数据,read返回0if(read > 0) {buffer.flip();debugRead(buffer);buffer.clear();log.debug("after read...{}", channel);}}}} }

总结

以上是生活随笔为你收集整理的netty-阻塞模式,非阻塞模式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。