Peter Penzov
Peter Penzov

Reputation: 1680

Thread sleep in connection

I have a network client which tries 3 times in a loop to connect to server. During this time I use sleep thread. Is there any way to replace Thread.sleep(700); with some code which skip the waiting period right after the client is connected.

NClient pc;

if (pc == null)
{
    try
    {
        Thread.sleep(700);
    }
    catch (InterruptedException x)
    {
        //TODO
    }

    if (pc != null)
    {
        outPrint.println("Connected");
        break;
    }
}

I would like to improve the user experience by reducing the waiting period in which the connection negotiation is in progress. What are the options in Java to do this?

Upvotes: 0

Views: 946

Answers (1)

Muel
Muel

Reputation: 4425

The answer to this question depends on the implementation of NClient. Typically, I'd use a connect timeout for this. The example below indicates how to do this with a Socket. I don't know what NClient is, so I can't give you an NClient example unfortunately.

Create a method that attempts to connect - up to 3 times

Socket connectToServer() {
  Socket socket = new Socket();
  final int connectTimeoutMs = 700;
  for (int i=0; i<3; i++) {
    try {
      // the call to connect blocks the current thread for a maximum of 700ms if it can't connect
      socket.connect(new InetSocketAddress("localhost", 8080), connectTimeoutMs);
    } catch (IOException e) {
      // failed to successfully connect within 700 milliseconds
      e.printStackTrace();
    }
  }
  return socket;
}

Use the above as follows

Socket socket = connectToServer();
if (socket.isConnected()) {
  // do stuff with the valid socket!
}

In short, use a connect timeout!

Upvotes: 1

Related Questions