netty-阻塞模式,非阻塞模式
生活随笔
收集整理的这篇文章主要介绍了
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.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-阻塞模式,非阻塞模式的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 网络编程BIO,NIO一
- 下一篇: 数据结构与算法:二分法