當(dāng)前位置:
首頁 >
netty-阻塞模式,非阻塞模式
發(fā)布時(shí)間:2025/6/15
14
豆豆
生活随笔
收集整理的這篇文章主要介紹了
netty-阻塞模式,非阻塞模式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
以下方法為阻塞模式(單線程)
只能干一件事。
以下方法為非阻塞模式(單線程)
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);// 創(chuàng)建服務(wù)器ServerSocketChannel ssc = ServerSocketChannel.open();// 非阻塞模式ssc.configureBlocking(false);// 綁定監(jiān)聽端口ssc.bind(new InetSocketAddress(8080));List<SocketChannel> channels = new ArrayList<>();// 有一個(gè)缺點(diǎn):沒有連接請求時(shí),也會(huì)不斷循環(huán)。// 沒有數(shù)據(jù)可讀時(shí),也會(huì)不斷循環(huán)。while(true) {//log.debug("connection...");// 建立與客戶端的連接SocketChannel sc = ssc.accept(); // 非阻塞,線程還會(huì)繼續(xù)運(yùn)行。如果沒有建立連接,sc是nullif(sc != null){log.debug("connected...{}",sc);sc.configureBlocking(false);channels.add(sc);}// 接受客戶端發(fā)送的數(shù)據(jù)for (SocketChannel channel : channels) {//log.debug("before read...{}",channel);int read = channel.read(buffer); // 非阻塞,線程仍然繼續(xù)運(yùn)行。如果沒有讀到數(shù)據(jù),read返回0if(read > 0) {buffer.flip();debugRead(buffer);buffer.clear();log.debug("after read...{}", channel);}}}} }總結(jié)
以上是生活随笔為你收集整理的netty-阻塞模式,非阻塞模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络编程BIO,NIO一
- 下一篇: 操作系统原理一