I want to connect to a remote server from thread and keep sending strings. If the connection gets refused the thread should keep polling the port until the server is up again. How can I handle this exception and keep my thread fro crashing? The server may not be up for long time but thread should run indefinitely.

```
public void SendMessage(String message){
    try {
        socket = new Socket(actuatorAddress, destPort.get());
        outToServer = socket.getOutputStream();
        out = new DataOutputStream(outToServer);
        out.flush();
        out.write(message.getBytes());
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

```

I changed some part of the code as below. For first time called Connect function and then subsequently called Send Message function through thread. The delay added to reconnecting helped reduce time lag recurred due to connecting to non existing server. Still think that there might be a better solution to the basic problem.

```
public boolean ConnectToActuator() {
    try {
        if(actuatorAddress.isReachable(2000)){
            socket = new Socket();
            socket.setPerformancePreferences(1, 2, 0);
            socket.setTcpNoDelay(false);
            socket.setSendBufferSize(32);
            socket.connect(new InetSocketAddress(actuatorAddress, destPort.get()));
            outToServer = socket.getOutputStream();
            out = new DataOutputStream(outToServer);
            connected = true;
            disconnectedTimeout = 0;
        }
    }catch (ConnectException e) {
        // TODO Auto-generated catch block
        System.out.println(e.getMessage());
    }catch (IOException ex) {
        connected = false;
        System.out.println(ex.getMessage());
    }
    return connected;
}

public boolean SendToActuator(String message) {
    if(connected == false){ //socket.isOutputShutdown()
        disconnectedTimeout++;
        if(disconnectedTimeout>20){
            disconnectedTimeout = 0;
            ConnectToActuator();
        } else {
            return connected;
        }
    }
    try {
        out.flush();
        out.writeBytes(message);
        disconnectedTimeout = 0;
        connected = true;
    } catch (UnknownHostException uhe) {
        connected = false;
        System.out.println(uhe.getMessage());
    } catch (IOException ioe) {
        connected = false;
        System.out.println(ioe.getMessage());
    }
    return connected;
}

```