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