How to close a non-blocking socket?

I am writing a server program using Java not blocking the SocketChannel. Sometimes I want to send a response message and then close the channel, like the following code.

However, the close () method aborts the write () method, I get java.nio.channels.ClosedChannelException and the message is not sent.

I can post a thread and wait 1-2 seconds before closing the channel, but I find it so wasteful to create another thread.

What is the appropriate way to close the SocketChannel during pending operations?

String msg = "Wrong password!";
channel.write(ByteBuffer.wrap(msg.getBytes()));
channel.close();
+3
source share
1 answer

. socket(). setSoLinger (true, MAX_SECONDS_FOR_OUTPUT_TO_DRAIN);

. . , close() MAX_SECONDS_FOR_OUTPUT_TO_DRAIN .

-1

Source: https://habr.com/ru/post/1778204/


All Articles