gpt4 book ai didi

java - 如何同步我的端口扫描仪,以便结果按照执行顺序显示?

转载 作者:行者123 更新时间:2023-11-30 04:33:46 27 4
gpt4 key购买 nike

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

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

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

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

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

我正在考虑创建一个线程号并将结果保存在数组中以便执行它们(至少我是这么认为的)。

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

最佳答案

尝试 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();

关于java - 如何同步我的端口扫描仪,以便结果按照执行顺序显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13985269/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com