简体   繁体   English

如何正确关闭无阻塞套接字通道?

[英]How to close a non blocking socket channel properly?

I'm writing a server program using Java non-blocking SocketChannel. 我正在使用Java非阻塞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. 但是,close()方法中断了write()方法,我得到了一个java.nio.channels.ClosedChannelException并且消息没有发送。

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. 我可以弹出一个线程并等待1-2秒,然后再关闭频道,但是我觉得创建另一个线程非常浪费。

What is the proper way to close a SocketChannel while there are pending operations? 有未决操作时关闭SocketChannel的正确方法是什么?

String msg = "Wrong password!";
channel.write(ByteBuffer.wrap(msg.getBytes()));
channel.close();

channel. 渠道。 socket (). 套接字 ()。 setSoLinger (true, MAX_SECONDS_FOR_OUTPUT_TO_DRAIN); setSoLinger (true,MAX_SECONDS_FOR_OUTPUT_TO_DRAIN);

See info on the linger option . 请参阅有关linger选项的信息 As mentioned, it will cause close() to block for up to MAX_SECONDS_FOR_OUTPUT_TO_DRAIN seconds. 如前所述,它将导致close()阻塞最多MAX_SECONDS_FOR_OUTPUT_TO_DRAIN秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM