【发布时间】:2012-08-04 14:39:42
【问题描述】:
下面的代码是我用来创建端口扫描器的代码,但是,当我单击“扫描”时,它会执行,但 gui 会冻结,直到完成扫描,是否有任何可能的方法允许它在执行其他操作的同时执行其他操作扫描?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class PortScannerGUI extends JFrame implements ActionListener
{
JPanel Panel = new JPanel(null);
JTextField Field = new JTextField();
JButton Button = new JButton();
JTextArea Area = new JTextArea();
JButton limit = new JButton("limit");
public PortScannerGUI()
{
super();
setSize(350, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
LoadUI();
}
public void LoadUI()
{
Area.setBounds(20, 50, 310, 310);
Area.setBorder(BorderFactory.createLineBorder(Color.BLUE));
Area.setEditable(false);
Field.setBounds(20, 10, 200, 35);
Button.setBounds(230, 10,100, 35);
Button.setText("Scan");
Button.addActionListener(this);
Panel.add(Field);
Panel.add(Area);
Panel.add(Button);
add(Panel);
setVisible(true);
}
public static void main(String[] args)
{
PortScannerGUI Main = new PortScannerGUI();
}
@Override
public void actionPerformed(ActionEvent arg0)
{
Thread Runner = new Thread();
Runner.start();
int j=0;
String str = Field.getText();
for(int i=1;i<str.length();i++)
{
if(str.substring(i-1, i).equals("."))
{
j++;
}
}
if(!str.equals("") || j==4 || j==6)
{
try
{
InetAddress IP = InetAddress.getByName(str);
PortScanner P = new PortScanner(IP);
}
catch (Exception e){}
}
else
{
JOptionPane.showMessageDialog(null, "Not an IP address");
}
}
}
上面的代码是GUI部分的代码,下面是实际扫描端口的代码..
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class PortScanner
{
public PortScanner(InetAddress iA)
{
for (int port = 1; port <= 65535; port++)
{
try
{
Socket s = new Socket(iA, port);
System.out.println("Port " + port + " is open");
s.close();
}
catch(IOException e)
{
}
}
}
}
【问题讨论】:
标签: java for-loop freeze port-scanning