你如何干净地关闭AsynchronousSocketChannel?

Nic*_*olt 8 java nio nio2

我的服务器使用a AsynchronousServerSocketChannel来侦听客户端连接CompletionHandler.当接受客户端连接时,将AsynchronousSocketChannel再次使用a CompletionHandler来读取,以便在没有超时的情况下接收数据.

到目前为止,我的客户端连接,写入服务器读取的数据,它能够响应通过同一个套接字将数据发送回客户端.

当我的客户端终止时,它会调用AsynchronousSocketChannel.close(),以关闭套接字.进行此调用时,服务器正在等待从套接字读取数据.

我曾期望AsynchronousSocketChannel.close()客户端上的调用转换为服务器上CompletionHandler.completed读取长度为的回调-1,表明套接字已关闭,但回调是CompletionHandler.failed以下异常:

java.io.IOException: The specified network name is no longer available.
  at sun.nio.ch.Iocp.translateErrorToIOException(Iocp.java:309)
  at sun.nio.ch.Iocp.access$700(Iocp.java:46)
  at sun.nio.ch.Iocp$EventHandlerTask.run(Iocp.java:399)
  at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:744)    
Run Code Online (Sandbox Code Playgroud)

客户端应如何关闭套接字,以免在服务器上看到错误?

Ale*_*dov 3

关于 close 的文档说它会在另一端导致 AsynchronousCloseException 或 ClosedChannelException 。

为此,completed(-1)客户端应调用shutdownInput

但是,我会将 AsynchronousCloseException 和 ClosedChannelException 视为正常关闭,以及已完成(-1)。