1

我创建了一个类,它将尝试扫描某些主机的端口。

问题是我以随机方式得到结果,或者 w/e 先完成。

我如何确保在执行此端口扫描时显示结果?

测试方法(对不起谷歌):

public class SimplePortScanner
{
    public static void main(String[] args)
    {
        for(int i = 78; i < 85; i++)
        {
            new Scanner("google.com", i).start();
        }
    }
}

端口扫描方法:

import java.net.*;

public class Scanner extends Thread
{
    private String address;
    private int port;

    Scanner(String address, int port)
    {
        super(address);
        this.address = address;
        this.port = port;
    }

    public void run()
    {
        try
        {
            SocketAddress sa = new InetSocketAddress(address, port);
            Socket socket = new Socket();
            socket.connect(sa, 2000);

            System.out.println("Port in use: " + port);

            socket.close();
        }
        catch (Exception e)
        {
            System.out.println("Port not in use: " + port);
        }
    }
}

我正在考虑创建一个线程号并将结果保存在数组中,以便它们被执行(至少我是如何看待它的)。

如何正确执行此操作?我只是在搞乱线程,如果我在这里搞砸了一些东西,我很抱歉......

4

1 回答 1

2

试试 java.util.concurrent

class Scanner implements Callable<Boolean> {
    ....

    @Override
    public Boolean call() {
        try {
            ....
            return true;
        } catch(Exception e) {
            return false;
        }
    }
}

ExecutorService ex = Executors.newCachedThreadPool();
List<Scanner> tasks = new ArrayList<>();
for (int i = 78; i < 85; i++) {
    tasks.add(new Scanner("google.com", i));
}
List<Future<Boolean>> list = ex.invokeAll(tasks);
for(int i = 0; i < tasks.size(); i++) {
    if (list.get(i).get()) {
        System.out.printf("Port is in use: %d", tasks.get(i).port());
    } else {
        System.out.printf("Port is not in use: %d", tasks.get(i).port());
    }
}
// dont forget to shutdown executor
ex.shutdown();
于 2012-12-21T06:43:27.580 回答