如何正确关闭非阻塞套接字通道?
我正在使用 Java 非阻塞 SocketChannel 编写服务器程序。有时我想发送一条回复消息,然后关闭频道,如下面的代码。
但是, close() 方法中断了 write() 方法,我收到 java.nio.channels.ClosedChannelException 并且消息未发送。
我可以弹出一个线程并等待 1-2 秒再关闭通道,但我觉得创建另一个线程太浪费了。
当有待处理的操作时关闭 SocketChannel 的正确方法是什么?
String msg = "Wrong password!";
channel.write(ByteBuffer.wrap(msg.getBytes()));
channel.close();
I'm writing a server program using Java non-blocking SocketChannel. Sometimes I want to send a reply message and then close the channel, like the following code.
However, the close() method interrupts the write() method, I get a java.nio.channels.ClosedChannelException and the message is not sent.
I can pop a thread and wait for 1-2 seconds before closing the channel, but I feel it's so wasteful to making another thread.
What is the proper way to close a SocketChannel while there are pending operations?
String msg = "Wrong password!";
channel.write(ByteBuffer.wrap(msg.getBytes()));
channel.close();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通道。套接字().setSoLinger(true, MAX_SECONDS_FOR_OUTPUT_TO_DRAIN);
查看有关延迟选项。如前所述,它将导致 close() 阻塞长达 MAX_SECONDS_FOR_OUTPUT_TO_DRAIN 秒。
channel.socket().setSoLinger(true, MAX_SECONDS_FOR_OUTPUT_TO_DRAIN);
See info on the linger option. As mentioned, it will cause close() to block for up to MAX_SECONDS_FOR_OUTPUT_TO_DRAIN seconds.