If another application on the PC is connected to the same remote IP address, a java application will fail to connect properly.
This can also happen when a exits abruptly without closing the socket channel. The connection can be blocked and it is impossible to connect during a subsequent session.
What can I do to ensure that no matter the state of the connection in the underlying OS, my program will connect 100% of the time ?
I am looking for a cross platform solution (Windows & Ubuntu)
public void connect() throws CommunicationIOException {
try {
if (isConnected()) {
return;
}
socket = SocketChannel.open();
socket.socket().connect(new InetSocketAddress(getHostname(), getPort()), getConnectionTimeout());
if (!isConnected()) {
throw new CommunicationIOException("Failed to establish the connection");
}
socket.configureBlocking(false);
} catch (final IOException ex) {
throw new CommunicationIOException(
"An error occurred while connecting to " + getHostname() + " on port " + getPort(), ex);
}
}
.
public boolean isConnected() {
if (socket == null) {
return false;
} else {
return socket.isConnected();
}
}
.
public void close() throws CommunicationIOException {
if (socket != null) {
try {
socket.close();
} catch (final IOException ex) {
throw new CommunicationIOException(
MessageFormat.format(
"An error occurred while attempting to close the connection to {}:{}",
getHostname(), getPort()), ex);
}
}
}