Nick Silvestri
Nick Silvestri

Reputation: 321

Continuously connecting to a server via a Socket until a connection is established

I have a client that I want to try to continuously connect to a server until a connection is established (i.e. until I start the server).

clientSocket = new Socket();
while (!clientSocket.isConnected()) {
    try {
        clientSocket.connect(new InetSocketAddress(serverAddress, serverPort));
    } catch (IOException e) {
        e.printStackTrace();
    }

    // sleep prevents a billion SocketExceptions from being printed,
    // and hopefully stops the server from thinking it's getting DOS'd
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

After the first attempt, I get a ConnectionException; expected, since there is nothing to connect to. After that, however, I start getting SocketException: Socket closed which doesn't make sense to me since clientSocket.isClosed() always returns false, before and after the connect() call.

How should I change my code to get the functionality I need?

Upvotes: 0

Views: 153

Answers (1)

user207421
user207421

Reputation: 310840

You can't reconnect a Socket, even if the connect attempt failed. You have to close it and create a new one.

Upvotes: 2

Related Questions