请修改代码,让它使用NIO
时间: 2024-02-25 13:53:07 浏览: 22
好的,修改后的代码如下:
```
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
public class PortScanner {
private String host;
private int minPort;
private int maxPort;
private int timeout;
public PortScanner(String host, int minPort, int maxPort, int timeout) {
this.host = host;
this.minPort = minPort;
this.maxPort = maxPort;
this.timeout = timeout;
}
public void scan() throws IOException {
Selector selector = Selector.open();
for (int port = minPort; port <= maxPort; port++) {
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_CONNECT);
channel.connect(new InetSocketAddress(host, port));
}
while (selector.select(timeout) > 0) {
for (SelectionKey key : selector.selectedKeys()) {
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key.channel();
if (channel.finishConnect()) {
System.out.println("Port " + channel.socket().getPort() + " is open");
} else {
System.out.println("Port " + channel.socket().getPort() + " is closed");
}
channel.close();
}
}
selector.selectedKeys().clear();
}
selector.close();
}
}
```
这个版本的代码使用了Java的NIO包中的SocketChannel和Selector类,将连接端口的过程改为非阻塞式操作。首先,通过for循环创建一个SocketChannel,然后将其注册到Selector中。在连接端口时,由于SocketChannel的非阻塞模式,连接方法会立即返回,这时需要通过Selector的select方法来等待连接完成。在连接完成后,会通过SelectionKey的isConnectable方法来判断连接是否成功,如果成功则输出端口号,否则输出端口关闭。最后,需要关闭连接和Selector对象。