技术开发 频道

Java7 NIO.2入门:异步通道API教程

  利用 Future 对象,当前线程可阻塞来等待结果:

AsynchronousSocketChannel worker = future.get();

  此处,其阻塞超时时间为 10 秒:

AsynchronousSocketChannel worker = future.get(10, TimeUnit.SECONDS);

  或者轮询操作的当前状态,还可取消操作:

if (!future.isDone()) {
    future.cancel(
true);
}

  cancel() 方法可利用一个布尔标志来指出执行接受的线程是否可被中断。这是个很有用的增强;在以前的 Java 版本中,只能通过关闭套接字来中止此类阻塞 I/O 操作。

  客户端设置

  接下来,要通过打开并连接与服务器之间的 AsynchronousSocketChannel,来设置客户端:

AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
    client.connect(server.getLocalAddress()).get();

  一旦客户端与服务器建立连接,可通过使用字节缓存的通道来执行读写操作,如清单 1 所示:

  清单 1. 使用读写字节缓存

// send a message to the server
ByteBuffer message
= ByteBuffer.wrap("ping".getBytes());
client.write(message).get();

// read a message from the client
worker.read(readBuffer).get(
10, TimeUnit.SECONDS);
System.out.println(
"Message: " + new String(readBuffer.array()));

  还支持异步地分散读操作与写操作,该操作需要大量字节缓存。

  新异步通道的 API 完全从底层套接字中抽取掉:无法直接获取套接字,而以前可以调用 socket() ,例如,SocketChannel。引入了两个新的方法 —— getOption 和 setOption —— 来在异步网络通道中查询并设置套接字选项。例如,可通过 channel.getOption(StandardSocketOption.SO_RCVBUF) 而不是 channel.socket().getReceiveBufferSize(); 来检索接收缓存大小。

0
相关文章