Java NIO之通道Channel

channel与流的区别:java

  • 流基于字节,且读写为单向的。
  • 通道基于快Buffer,能够异步读写。除了FileChannel以外都是双向的。

 

channel的主要实现:服务器

  • FileChannel
  • DatagramChannel:UDP读写
  • SocketChannel:TCP读写
  • ServerSocketChannel

支持scatter/gather(分散和汇集)dom

        1. 分散(scatter)从Channel中读取是指在读操做时将读取的数据写入多个buffer中。所以,Channel将从Channel中读取的数据“分散(scatter)”到多个Buffer中。
          汇集(gather)写入Channel是指在写操做时将多个buffer的数据写入同一个Channel,所以,Channel 将多个Buffer中的数据“汇集(gather)”后发送到Channel。
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body   = ByteBuffer.allocate(1024);
ByteBuffer[] bufferArray = { header, body };
channel.read(bufferArray);

通道的建立:异步

除了FileChannel以外,都使用open建立。socket

FileChannel的建立以下:spa

RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();

 

Socket通道.net

分别对应java.net包中的Socket对象ServerSocket、Socket和DatagramSocket;Socket通道被实例化时,都会建立一个对等的Socket对象。code

 

Socket通道能够运行非阻塞模式而且是可选择的,非阻塞I/O与可选择性是紧密相连的,这也正是管理阻塞的API要在 SelectableChannel中定义的缘由。设置非阻塞很是简单,只要调用configureBlocking(false)方法便可。若是须要中 途更改阻塞模式,那么必须首先得到blockingLock()方法返回的对象的锁。对象

 

ServerSocketChannel实例:blog

1. 使用对等socket来bind监听。

2. 非阻塞状态下,accept在无链接时当即返回null

ByteBuffer buffer = ByteBuffer.wrap("Hello World".getBytes());
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(12345));
ssc.configureBlocking(false);
for (;;) {
    System.out.println("Waiting for connections");
    SocketChannel sc = ssc.accept();
    if (sc == null)
       TimeUnit.SECONDS.sleep(2000);
   else {
        System.out.println("Incoming connection from:" + sc.socket().getRemoteSocketAddress());
        buffer.rewind();
        sc.write(buffer);
        sc.close();
    }
}

 

  • SocketChannel 
           相对于ServerSocketChannel,它扮演客户端,发起到监听服务器的链接,链接成功后,开始接收数据。 
           调用它的open()方法仅仅是打开但并未链接,要创建链接须要紧接着调用connect()方法;也能够两步合为一步,调用open(SocketAddress remote)方法。 
           你会发现connect()方法并未提供timout参数,做为替代方案,你能够用isConnected()、isConnectPending()或finishConnect()方法来检查链接状态。
  • 1. isConnected判断是否已经创建
  • 2. finishConnect在非阻塞套接字上阻塞等待链接成功

 

非阻塞的read在无数据时当即返回0

  •  
  • DatagramChannel         它是无链接的,它既能够做为服务器,也能够做为客户端。
相关文章
相关标签/搜索