Itzik.B
Itzik.B

Reputation: 1076

establish http request with Timed out - Java

I'm looking for a way to establish an HTTP Request via java to ensure the server is alive.

for example I want to scan ip addresses range 192.168.1.1-255 and print a log with the living server.,

I want to setTimeOut for 3Seconds when the HTTP response is delayed for some reason.

I have tried to do it this way:

try {
            Socket s = new Socket(InetAddress.getByName("192.168.1.2"), 80);
            s.setSoTimeout(3 * 1000);
            PrintWriter pw = new PrintWriter(s.getOutputStream());
            pw.println("GET / HTTP/1.1");
            pw.println("Host: stackoverflow.com");
            pw.println("");
            pw.flush();
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String t;
            while ((t = br.readLine()) != null) System.out.println(t);
            br.close();
        } catch (SocketTimeoutException e) {
            System.out.println("Server is dead.");
        } catch (ConnectException e) {
            System.out.println("Server is dead.");
        }

But it's seem to be not waiting at all when the request is taking longer than 3000millis.

Thanks!

Upvotes: 0

Views: 86

Answers (1)

YuTendo
YuTendo

Reputation: 339

I think you confused the different timeouts. If you want to abort the connection attempt after three seconds without any response, then you should establish the connection as follows:

Socket clientSocket = new Socket();
clientSocket.connect(new InetSocketAddress(target, 80), 3 * 1000);

where target is any IP address. The following line essentially set the timeout value for reading/waiting for the inputstream -after the connection was established. So it has not effect on establishing the connection itself. However, after the connection was established it would interrupt the "read inputstream" step after three seconds (by throwing an exception).

clientSocket.setSoTimeout(3 * 1000);

However, if you want to limit also the time for reading the inputstream without throwing an exception, then you need a costum solution: Is it possible to read from a InputStream with a timeout?

The following running example worked very well in my local network. It tried to connect for at most three seconds and detected all running webservers.

public class Main {
    public static void main(String[] args) {
        String net = "192.168.168."; // this is my local network
        for (int i = 1; i < 255; i++) { // we scan the range 1-255
            String target = net + i;
            System.out.println("Try to connect to: " + target);
            try {
                Socket clientSocket = new Socket();

                // we try to establish a connection, timeout is three seconds
                clientSocket.connect(new InetSocketAddress(target, 80), 3 * 1000);
   
                // talk to the server
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
                out.println("GET / HTTP/1.1");
                out.println("Host: stackoverflow.com");
                out.println("");
                out.flush();
                BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String t;
                while ((t = br.readLine()) != null) System.out.println(t); // We print the answer of the server
                br.close();
                clientSocket.close();

                // server seems to be alive
                System.out.println("> Server is alive");
            } catch (SocketTimeoutException | ConnectException e) {
                System.out.println("> Server is dead");
            } catch (Exception e) { // This is not nice but this is also just a demo
                e.printStackTrace();
            }
        }
    }
}

Output (excerpt):

Try to connect to: 192.168.168.1
> Server is dead
Try to connect to: 192.168.168.2
> Server is dead
...
Try to connect to: 192.168.168.23
(answer of the server)
> Server is alive
...

Upvotes: 1

Related Questions