简体   繁体   中英

Keep trying to contact server until response comes

I need to write a program with machines P0, P1 such that either machine can be started first and needs to contact other. Lets say P1 starts then it needs to keep trying contacting P0 until it gets an acknowledgment from P0. How can I do this using socket programming in Java.

If an exception is raised saying that P0 is not running then it still needs to keep trying rather than throwing exception for that. Or even if it throws an exception, how can I handle exception in such a way that it again repeats same things. I know that P0 will be manually run in few min.

Here's what I am doing

int P1Ack = 1;

while(P1Ack != 1) // where P1Ack is the acknowledgment that P0 sends if it gets a message from P1
    {
               P1connectsP0();
    }


public void P1ConnectsP0()
{
      String str = "Hello";

        {
            Socket clientSock = new Socket(lamport.P0Ip, lamport.P0Port);
            ObjectOutputStream clientWriter = new ObjectOutputStream(clientSock.getOutputStream());
            ObjectInputStream clientReader = new ObjectInputStream(clientSock.getInputStream());
            clientWriter.writeObject(str);
            clientWriter.flush();
        }
        catch(IOException ex)
        {
            System.out.println("Error : P1 unable to talk to P0");
            ex.printStackTrace();
        }

You seem to be using a Socket object here, which is a TCP socket in Java. The TCP protocol guarantees delivery of packets, so you don't need to do manual acknowledgement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM