Click here to Skip to main content
15,887,979 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am trying to make 3 attempts from client side when server is down. After three attempts it will exit the program. Whatever I tried it works but within one time. when run the program it automatically make 3 attempts but I want separately like one time it will lost one attempt.
Thank you

What I have tried:

int attempt =3;
while(true) 
{
    try {
        Reconnect();
        text1.append("Successfully connected \n");
        textField1.setText("Connected");
        textField1.setBackground(Color.GREEN);
        break;
    } 
    catch (IOException e1) {
        attempt--;
        text1.append("you have left "+attempt+" attempt \n Try again\n");
    }
    if(attempt==0) {
        SendMailBySite();
        break;
    }
}
    
private void Reconnect() throws UnknownHostException, IOException {
    String hostName = "127.0.0.1";
    int portNumber = Integer.parseInt("5058");
    Socket socket = new Socket(hostName,portNumber);
}
Posted
Updated 3-Sep-18 23:02pm
v4
Comments
Richard MacCutchan 3-Sep-18 7:25am    
You need to run the try/catch block inside a repeating loop.
FerdouZ 3-Sep-18 22:13pm    
I tried already. It's not working.
Richard MacCutchan 4-Sep-18 3:50am    
What is not working? Please do not expect us to guess what your code is doing or what results you see and why they are wrong. If you do not provide proper details then we have no way of making useful suggestions.
FerdouZ 4-Sep-18 4:40am    
I update my code. As per your solution I put try/catch block inside the loop. Now, when I run this program it's running all the attempts together but I i want one attempts one time like a Login attempts.So, after three attempts it will exit.Actually I am doing in java swing Gui. Hope you will understand. If anything please ask in comment. Thank you
Richard MacCutchan 4-Sep-18 5:05am    
Now I have fixed the indentation in your code, it is a little easier to read. You correctly decrement the attempt counter in your catch block. However, at the end of the loop, if the attempt counter is zero you do not exit.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900