0
votes

I am working on a middleware application which creates and maintains TCP/IP connections to several servers. If the application detects that a connection has been lost, it will try to reconnect on a timer until the connection is reestablished.

The application is using java.nio.SocketChannel objects in non-blocking mode, with Selector/SelectionKey to handle the socket events.

Once a connection is lost, is it better to throw away the current SocketChannel object, and create a new one to reconnect (also get a new SelectionKey), or to reuse the same SocketChannel and SelectionKey (which I guess is invalid until connection is established again)?

1
to put it simply: you cant reuse the SocketChanngel - bestsss
noted. thanks! suprising to me, but the SocketChannel still reports isConnected() even after the connection is lost. - Sam Goldberg
unless closed isConnected() would return true, provided the connection was establish. After getting an exception or receiving EOF (-1) just close the channel. - bestsss
isConnected() doesn't magically become false when the peer disconnects. - user207421

1 Answers

2
votes

You must throw it away. When a connection is lost you must close the SocketChannel on your end to clean up the connection correctly. If you want to try to reconnect then just do exactly what you did the first time (createSocket, make non blocking, init connection etc).