简体   繁体   中英

How to close a non blocking socket channel properly?

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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