網站首頁 編程語言 正文
* Scattering:將數據寫入到buffer時,可以采用buffer數組,依次寫入 * Gathering:從buffer讀取數據時,可以采用buffer數組,依次讀取
示例代碼
public static void main(String[] args) throws IOException { //使用serversocketchannel和socketchannel,客戶端就用telnet連接 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); InetSocketAddress inetSocketAddress = new InetSocketAddress(8000); //綁定接口到socket,并啟動 serverSocketChannel.socket().bind(inetSocketAddress); ByteBuffer[] byteBuffers = new ByteBuffer[2]; byteBuffers[0] = ByteBuffer.allocate(5); byteBuffers[1] = ByteBuffer.allocate(3); //等待客戶端連接(telnet) SocketChannel socketChannel = serverSocketChannel.accept(); int messageLength = 8;//假定從客戶端接受8個字節 while(true){ int byteRead = 0; while(byteRead< messageLength){ long r = socketChannel.read(byteBuffers); byteRead +=r; System.out.println("byteRead"+byteRead); //使用流打印,看當前buffer的postion和limit Arrays.asList(byteBuffers).stream().map(buffer ->"postion=" +buffer.position()+",limit="+buffer.limit()).forEach(System.out::println); } //將所有的buffer反轉 Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.flip()); //將數據讀出顯示到客戶端 long byteWirte = 0; while(byteWirte<messageLength){ long l = socketChannel.write(byteBuffers); byteWirte+=l; } //將所有的buffer 運行claer Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.clear()); System.out.println("byteRead:"+byteWirte+"byteWrite"+byteWirte+"messagelength"+messageLength); } }
當使用telnet發送9個byte的數組時
?
?
當使用telnet再次發送6個byte的數組時
再次連續發送兩次一個byte
?
?由此可以看出Scattering的意思就像buffer數組像水杯一樣,將數據(水)倒入數組的第一個buffer,滿了的話,就向第二個buffer接著倒,一直到buffer數組都倒滿。
而Gathering就是在讀取的時候將按順序,數組里的buffer一個一個的倒出來,拼成一句完整的信息
原文鏈接:https://blog.csdn.net/gacellk/article/details/125836330
- 上一篇:linux引導和服務過程
- 下一篇:Linux如何設置SSH免密登錄
相關推薦
- 2022-05-25 ASP.NET?Core?6.0對熱重載的支持實例詳解_實用技巧
- 2022-05-17 Git 克隆指定分支的代碼
- 2022-11-01 Android串口通訊SerialPort的使用詳情_Android
- 2022-07-12 weui省市區三級聯動
- 2022-04-19 盤點分析C語言中少見卻強大的字符串函數_C 語言
- 2022-04-02 docker建立私有倉庫的過程_docker
- 2023-03-04 Python使用yaml模塊操作YAML文檔的方法_python
- 2022-08-04 python實現決策樹分類算法代碼示例_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支