netty

作者: cammsia | 来源:发表于2016-09-01 10:38 被阅读11次
  1. I/O 模型
  • 阻塞I/O模型(BIO)
  • 非阻塞I/O模型
  • I/O复用模型(select/poll;epoll)
    • select/poll: 顺序扫描fd是否就绪
    • epoll: 事件驱动,mmap同一块内存来减少内存复制
  • 信号驱动I/O模型(何时可以开始I/O操作)
    1. 数据准备时间内进程继续执行,准备好了执行信号处理程序
    2. 执行recvfrom,数据复制(内核空间到用户空间)时阻塞。
  • 异步I/O (何时I/O完成)
  1. BIO

    1. 第一种方案 :一个客户端连接一个线程处理
    2. 第二种方案: 客户端连接又线程池来处理
  2. FileChannel 示例

下面是一个使用FileChannel读取数据到Buffer中的示例:

Java代码 
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");  
FileChannel inChannel = aFile.getChannel();  
  
ByteBuffer buf = ByteBuffer.allocate(48);  
  
int bytesRead = inChannel.read(buf);  
while (bytesRead != -1) {  
  
System.out.println("Read " + bytesRead);  
buf.flip();  
  
while(buf.hasRemaining()){  
System.out.print((char) buf.get());  
}  
  
buf.clear();  
bytesRead = inChannel.read(buf);  
}  
aFile.close();  

注意 buf.flip() 的调用,首先读取数据到Buffer,然后反转Buffer,接着再从Buffer中读取数据。下一节会深入讲解Buffer的更多细节。

相关文章

网友评论

      本文标题:netty

      本文链接:https://www.haomeiwen.com/subject/qucasttx.html