日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(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();// 綁定監(jiān)聽端口ssc.bind(new InetSocketAddress(8080));List<SocketChannel> channels = new ArrayList<>();while(true) {log.debug("connection...");// 建立與客戶端的連接SocketChannel sc = ssc.accept(); // 阻塞方法,線程停止運(yùn)行log.debug("connected...{}",sc);channels.add(sc);// 接受客戶端發(fā)送的數(shù)據(jù)for (SocketChannel channel : channels) {log.debug("before read...{}",channel);channel.read(buffer); // 阻塞方法,線程停止運(yùn)行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);// 創(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。