使用超时-Java

问题描述

我正在寻找一种通过java建立HTTP请求以确保服务器处于活动状态的方法

例如,我想扫描IP地址范围192.168.1.1-255,并使用活动服务器打印日志。

由于某种原因HTTP响应延迟时,我想setTimeOut停留3秒。

我尝试过这种方式:

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.");
        }

但是,当请求花费的时间超过3000毫秒时,似乎根本就没有等待。

谢谢!

解决方法

我认为您混淆了不同的超时时间。如果要在三秒钟后中止连接尝试而没有任何响应,则应按以下方式建立连接:

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

其中target是任何IP地址。在建立连接之后,以下行实质上设置了用于读取/等待输入流的超时值。因此,它对建立连接本身没有影响。但是,建立连接后,它将在三秒钟后(通过引发异常)中断“读取输入流”步骤。

clientSocket.setSoTimeout(3 * 1000);

但是,如果您还想限制读取输入流的时间而不会引发异常,那么您需要一种Costum解决方案: Is it possible to read from a InputStream with a timeout?

以下正在运行的示例在我的本地网络中效果很好。它尝试最多连接三秒钟,并检测到所有正在运行的Web服务器。

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,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();
            }
        }
    }
}

输出(节选):

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
...

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...