1. 什么是Channel
?
channel
表示的是在一个实体上打开的连接
实体:
- a hardware device
- a file
- a network socket
- a program component that is capable of performing one or more distinct I/O operations, for example reading or writing
2. Channel
有哪些状态?
Channel
只有open
和close
两种状态,二者的转换状态如下:
$$
\text{open} \longrightarrow \text{close} \
\text{close} \not\longrightarrow \text{open}
$$
有API可以查看一个channel
是不是open
状态: isOpen
3. Channel
的几个直接接口
3.1 WritableByteChannel
可以往其中写入bytes
的channel
,几乎总是在一个时间只有一个写操作作用于其上,是否能并发写还得看具体实现
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
,具体还是得看实现, 例如:
- 处于
non-block
模式的socket channel
,只会读取socket输入buffer
中的数据,不会多读 - 从一个
file channel
中最多只能读取到文件中剩余的数据 -
block
模式下,会读取channel
中所有的数据直到最后一个byte
3.3 AsynchronousChannel
支持异步IO操作的channel
异步IO操作通常可以分为以下2种形式:
Future<V> operation(...)
void operation(... A attachment, CompletionHandler<V, ? super A> handler)
param | desc |
---|---|
operation |
read/write |
V |
IO操作的结果类型 |
A |
附加于IO操作之上的对象类型,提供一个``context` |
例如:
// AsynchronousFileChannel
// read操作的结果是读到的byte的个数,即V为Integer
public abstract <A> void read(ByteBuffer dst,
long position,
A attachment,
CompletionHandler<Integer,? super A> handler);
public abstract Future<Integer> read(ByteBuffer dst, long position);
public abstract <A> void write(ByteBuffer src,
long position,
A attachment,
CompletionHandler<Integer,? super A> handler);
public abstract Future<Integer> write(ByteBuffer src, long position);
3.4 NetworkChannel
socket channel
NetworkChannel bind(SocketAddress local) throws IOException;
<T> NetworkChannel setOption(SocketOption<T> name, T value) throws IOException;
3.5 InterruptibleChannel
可以异步关闭和中断的channel