Closing a socket channel asynchronously

I have a single threaded non-blocking IO server written in Java using nio.

When I finished recording the connection, I want to close it.

Does the channel lock the channel until all buffered records are acknowledged by the receiver?

It would be useful to know if it succeeded or not when it was asynchronously closed, but I could live with any errors in closing that are ignored.

Is there a way to tune this, for example. with setSoLinger() (and what settings would be appropriate?)

(A general discussion outside of Java about Linux and other OSes would be helpful in this regard)

+4
source share
2 answers

Closing in non-blocking mode does not block.

You can put the channel into lock mode, set a positive delay timeout and close it, and it would block until the delay timeout when the socket send buffer was empty, but, alas, Java does not throw an exception if the delay timeout expires, therefore, you cannot know if all the data has passed. I reported this error ten or more years ago, and she returned “will not fix” due to compatibility issues. If you can wait for Java 7 to appear, I believe that nio2 has fixed it, of course I asked for it, but who knows when it will be?

And even if you have it all, all you know is that the data was sent. You do not know anything about this received or processed by the recipient application. If you need to, you must create it in your application protocol.

+3
source

I'm not sure what is actually happening, but I know that close() includes flush() (except for PrintStream and PrintWriter ...).

So my approach would be to add connections to the queue and process this queue in the second thread (including error handling).

I understand that your server is single-threaded, but the second thread is not that expensive, the complexity of the problem is low, and the solution will be easy to understand which one is supported.

+1
source

All Articles