传统的IO中,都是基于字节流/字符流进行操作的,而在NIO中则是基于通道(channel)和缓冲(buffer)进行操作的,其中的channel虽然模拟了流的概念,实则大不相同。
通道必须结合Buffer,不能直接像通道中读或写数据,结构如下:
所有的通道都有这两种操作:检查通道的开启状态和关闭通道。从Channel接口引申出的其他接口都是面向字节的子接口,也就是说通道本质上都是对自己缓冲区进行操作的。
这里只介绍SocketChannel (通过TCP读写网络数据)、DatagramChannel (通过UDP读写网络中的数据)
SocketChannel
ava NIO中的SocketChannel是一个连接到TCP网络套接字的通道,它是Socket类的对等类,通常SocketChannel用在客户端以向服务器发起
连接请求。每个SocketChannel对象创建时都关联一个对等的Socket对象。同样SocketChannel可以运行在非阻塞模式下。
- SocketChannel的使用
可以通过以下2种方式创建SocketChannel:
- 打开一个SocketChannel并连接到互联网上的某台服务器
- 一个新连接到达ServerSocketChannel时,会创建一个SocketChannel
一、 创建SocketChannel
通过SocketChannel的静态方法open()创建SocketChannel对象.此时通道虽打开,但并未连接,此时如果进行I/O操作会抛出NotYetConnectedException异常。
二、连接指定服务器
通过SocketChannel对象的connect()连接指定地址。该通道一旦连接他将保持连接状态直到被关闭。可通过isConnected()来确定某个SocketChannel当前是否已连接。
三、从SocketChannel读数据
利用SocketChannel对象的read()将数据读取到Buffer
四、向SocketChannel写数据
利用SocketChannel对象的write()将Buffer的数据写入。
五、关闭SocketChannel
利用SocketChannel对象的close()方法
当SocketChannel在非阻塞模式下异步调用connect(), read() 和write()时,需要注意connect(),write(),read()方法的行为:
如果SocketChannel在非阻塞模式下,此时调用connect(),该方法可能在连接建立之前就返回了。为了确定连接是否建立,可以调用finishConnect()的方法。
1
2
3
4
5
6
7socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(URL,port )); while(! socketChannel.finishConnect() ){ //wait, or do something else... }
非阻塞模式下,write()方法在尚未写出任何内容时可能就返回了。所以需要在循环中调用write()。
非阻塞模式下,read()方法在尚未读取到任何数据时可能就返回了。所以需要关注它的int返回值.
SocketChannel完整示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public class SocketChannelTest { private int size=1024; public void connectServer() throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999)); ByteBuffer byteBuffer=ByteBuffer.allocate(size); byteBuffer.put(new String("hello server").getBytes()); byteBuffer.flip(); while (byteBuffer.hasRemaining()) { socketChannel.write(byteBuffer); } } public static void main(String[] args) throws IOException { new SocketChannelTest().connectServer(); } }
最后
以上就是自然诺言最近收集整理的关于netty的channel的分类的全部内容,更多相关netty内容请搜索靠谱客的其他文章。
发表评论 取消回复