Java Channel

1. 什么是Channel?

channel表示的是在一个实体上打开的连接

实体:

  1. a hardware device
  2. a file
  3. a network socket
  4. a program component that is capable of performing one or more distinct I/O operations, for example reading or writing

2. Channel有哪些状态?

Channel只有openclose两种状态,二者的转换状态如下:
$$
\text{open} \longrightarrow \text{close} \
\text{close} \not\longrightarrow \text{open}
$$
有API可以查看一个channel是不是open状态: isOpen

3. Channel的几个直接接口

3.1 WritableByteChannel

可以往其中写入byteschannel,几乎总是在一个时间只有一个写操作作用于其上,是否能并发写还得看具体实现

public int write(ByteBuffer src) throws IOException;

该方法的调用时产生很多异常类型可以看出使用该方法的一些注意事项:

method desc
NonWritableChannelException If this channel was not opened for writing
ClosedChannelException If this channel is closed
AsynchronousCloseException If another thread closes this channel while the write operation is in progress
ClosedByInterruptException If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt status

3.2 ReadableByteChannel

WritableByteChannel相反,可以从该channel中读取数据到buffer

public int read(ByteBuffer dst) throws IOException;

读取数据到buffer中,并不一定会填满整个buffer,具体还是得看实现, 例如:

  1. 处于non-block模式的socket channel,只会读取socket输入buffer中的数据,不会多读
  2. 从一个file channel中最多只能读取到文件中剩余的数据
  3. block模式下,会读取channel中所有的数据直到最后一个byte

3.3 AsynchronousChannel

支持异步IO操作的channel

异步IO操作通常可以分为以下2种形式:

  1. Future operation(...)
  2. void operation(... A attachment, CompletionHandler handler)
param desc
operation read/write
V IO操作的结果类型
A 附加于IO操作之上的对象类型,提供一个``context`

例如:

// AsynchronousFileChannel
// read操作的结果是读到的byte的个数,即V为Integer
public abstract  void read(ByteBuffer dst,
                              long position,
                              A attachment,
                              CompletionHandler handler);
public abstract Future read(ByteBuffer dst, long position);

public abstract  void write(ByteBuffer src,
                               long position,
                               A attachment,
                               CompletionHandler handler);
public abstract Future write(ByteBuffer src, long position);

3.4 NetworkChannel

socket channel

NetworkChannel bind(SocketAddress local) throws IOException;
 NetworkChannel setOption(SocketOption name, T value) throws IOException;

3.5 InterruptibleChannel

可以异步关闭和中断的channel

你可能感兴趣的:(Java Channel)