netty学习笔记08——Channel

netty学习笔记08——Channel

基本介绍

  1. NIO的通道(channel)类似流,但是有以下的区别:

    • 通道可以同时进行读写(双工),而流只能读或者只能写(单工)
    • 通道可以实现异步读写数据
    • 通道可以从缓冲读数据,也可以写数据到缓存
  2. Channel在NIO中是一个接口

    public interface Channel extends Closeable()

A channel represents an open connection to an entity such as a hardware device, a file, a network socket, or a program component that is capable of performing one or more distinct I/O operations, for example reading or writing.
A channel is either open or closed. A channel is open upon creation, and once closed it remains closed. Once a channel is closed, any attempt to invoke an I/O operation upon it will cause a ClosedChannelException to be thrown. Whether or not a channel is open may be tested by invoking its isOpen method.
Channels are, in general, intended to be safe for multithreaded access as described in the specifications of the interfaces and classes that extend and implement this interface.

通道表示与诸如硬件设备,文件,网络套接字或程序组件之类的实体的开放连接,该实体能够执行一个或多个不同的I / O操作(例如,读取或写入)。
通道是打开的还是关闭的。 通道在创建时打开,一旦关闭,它便保持关闭状态。 通道一旦关闭,任何在其上调用I / O操作的尝试都将引发ClosedChannelException。 可以通过调用isOpen方法来测试通道是否打开。
通常,通道的目的是确保多线程访问的安全,如接口规范以及扩展和实现此接口的类中所述。

  1. 常用的channel包括FileChannel(文件io)、DatagramChannel(UDP)、ServerSocketChannel(TCP服务器)和SocketChannel(TCP客户端)

netty学习笔记08——Channel

  1. FileChannel主要用来对本地文件进行IO操作,常见的方法有
    1. public int read(ByteBuffer dst)从通道读取数据并放到缓冲区中
    2. public int write(ByteBuffer src)把缓冲区的数据写入到通道中
    3. public long transferFrom(ReadableByteChannel src, long position, long count)从目标通道复制数据到当前通道(零拷贝)
    4. public long transferTo(long position, long count, WritableByteChannel target)从当前通道复制数据到目标通道(零拷贝)