Hi all,
I would like to write
java class that will connet to certain host and port, and stay behind, when connection error occurs, it will detect and try to reconnect silently. how do i make this kind of class for both performance and reliablity of connection.
import java.net.*;
import java.io.*;
public class SolidConnector implements Runnable {
private Socket socket;
private
String host;
private int port;
private int reconnectTime = 3000;
...
public SolidConnector(String host,int port){
socket = new Socket();
this.host = host;
this.port = port;
}
public boolean connect(){
try {
socket= new Socket(host,port);
System.out.println ("connected to" +socket.getInetAddress().getHostName());
return true;
}catch (Exception ex) {
//fail
}
return false;
}
public void run(){
int counter = 0;
while(!connect()){
try {
System.out.println ("connecting..."+ ++counter);
Thread.sleep(reconnectTime);
}
catch (Exception ex) {
}
}
while(true){
if(stopped) break;
try {
//nothing do, give cpu to other threads
Thread.sleep(2000);
//i want to detect connection is ok or not
//if connection got problem it throws Connction reset exception
socket.getInputStream().read();
}catch (IOException ex) {
System.out.println ("Connection Lost!");
reconnect();
}catch (InterruptedException ie){
}
}
}
public void reconnect() {
socket = null;
int counter = 0;
while(!connect()){
try {
System.out.println ("reconnecting..."+ ++counter);
Thread.sleep(reconnectTime);
}
catch (InterruptedException ex) {
//interrupted
}
}
}
public void stop(){
this.stopped = true;
}
public static void main (String[] args) {
SolidConnector sc = new SolidConnector("localhost",8000);
Thread t = new Thread(sc);
t.start();
}
}
The key point i like to know is how to detect when connection lost? I dont want to detect by socket.getInputStream().read() method. I would like to detect silently.
Please give suggestions for how to overcome this problem for performance and reliabily issues.
Thanks in advance,
kaze