我的服务器使用 AsynchronousServerSocketChannel
,它使用 CompletionHandler
监听客户端连接。当客户端连接被接受时,AsynchronousSocketChannel
被读取,再次使用 CompletionHandler
接收没有超时的数据。
到目前为止一切顺利,我的客户端连接,写入服务器读取的数据,服务器能够通过相同的套接字响应将数据发送回客户端。
当我的客户端终止时,它调用 AsynchronousSocketChannel.close()
来关闭套接字。进行此调用时,服务器正在等待从套接字读取数据。
我曾预计在客户端调用 AsynchronousSocketChannel.close()
会转换为对读取长度为 -1 的
在服务器上,表明套接字已关闭,但回调是 CompletionHandler.completed
的回调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)
客户端应该如何关闭套接字,以免在服务器上被视为错误?
最佳答案
documentation on close说它导致 另一端的 AsynchronousCloseException 或 ClosedChannelException。
要导致 completed(-1)
,客户端应该调用 shutdownInput .
但是,我会将 AsynchronousCloseException 和 ClosedChannelException 与 completed(-1) 一起视为正常关闭。
关于java - 如何干净利落地关闭 AsynchronousSocketChannel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20746091/