Sign in to follow this  

Proper way to close a Java SocketChannel

This topic is 2569 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm writing a game server using Java non-blocking SocketChannel. Sometimes I want to send a reply message and then close the channel, like the code below.

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?

code:

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

Share this post


Link to post
Share on other sites

This topic is 2569 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this