I have created a TCP client using Apache Mina. I have added a while loop to constantly check the liveness of the port. Once the connection is up on the server side, the loop is broken and the connection is made. i get the session from future and use it to communicate. Is there a better way to do this. instead of loop can i ask the connection to wait till its up.
while(true){
try {
ConnectFuture future = ioConnector.connect(new InetSocketAddress(Port),
new TriggerReceiverHandler(), SOCKET_CONFIG);
System.out.println("Message Receiver started and listening on port "+ Port);
Thread.sleep(1000);
session = future.getSession();
if(session != null)
break;
} catch (InterruptedException e) {
e.printStackTrace();
}catch(Exception ce){
if(ce.getCause() instanceof ConnectException)
System.out.println("Retrying connection");
}
}
Another question is, If the server is down and I want the server to keep waiting for the connection till its up, what should i do?
The answer is, As of now its not possible, as the connection state is known only when we attempt to connect. One modification is instead of the Thread.sleep(1000);
we can add future.join()
in version 1.0+ or add a listener for the future in case of 2.0+