Channel
Channel的简介
首先我们翻开JAVA API 文档中关于 java.nio.channels.Channel 的描述:
public interface Channel extends Closeable
- A nexus for I/O operations.
- 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.
从第2点我们可以看出,Channel与流类似,它是对原I/O中流的模拟,所有数据都要通过通道进行传输。Channel可以表示程序与硬件设备、文件、网络Socket或程序组件之间的一个打开的连接,但它又和流有些不大相同的地方,其中一个表现在其可以操作一个或者多个不同的 I/O操作,也就是说Channel既可以从通道中读取数据,又可以写数据到通道,而流的读写通常是单向的。
从第4点我们可以看出,实现Channel 接口的类或接口是多线程安全的。
Channel的实现
在Java NIO中,有众多Channel的实现,但一些最重要的通道的实现有如下几个:
- FileChannel => 从文件中读取数据
- DatagramChannel => 通过UDP读写网络中的数据
- SocketChannel => 通过TCP读写网络中的数据
- ServerSocketChannel => 监听新进来的TCP连接。对每一个新进来的连接都会创建一个SocketChannel。
针对以上几个Channel的实现,我们能粗略地了解到Channel的实现类们能打通程序与文件和网络Socket之间的通道,从而数据就可以通过Channel在程序与文件、网络间进行传输,并且这个传输是可以进行一个或者多个不同的I/O操作的,也可以说是双向的,例如读和写。如下图1所示:
图1. Channel连接程序与硬件设备、文件和网络Socket的连接
具体Channel的实现类们该如何使用,我们将在后面的内容中结合其他核心部分进行介绍。
参考资料:
[1]. Java 2 SE 7 Documentation Package java.nio
[2]. 并发编程网 Java NIO系列教程
[3]. Java nio 学习笔记(一) Buffer(缓冲区)与Channel(通道)的相关知识
原标题:Java NIO(二)Channel
关键词:JAVA