for loop语句总是如此

时间:2014-12-20 17:46:25

标签: java for-loop swingworker

长话短说我试图用非常简单的gui创建端口嗅探器。 没有工作者,端口嗅探器工作正常,但我想在每次找到开放端口时更新area1。添加worker后,“for”循环不循环。如果有人能告诉我问题所在,那就太好了。

import java.net.*;
import java.awt.*;
import java.awt.event.*;

// definējam galveno klasi
public class PortScanner extends JFrame implements ActionListener {
JButton poga1 = new JButton("palaist skaneri");
JTextField jt = new JTextField ("ievadam adresi",30);
SwingWorker worker;
JTextArea area1 = new JTextArea(5, 40);
//taisam konsturkoturu
public PortScanner(){
    //virsraksts
    super("Portu skaneris007");
    //definejam konteineru
    Container content = getContentPane();
    content.setBackground(Color.BLUE);
    //liekam konteineri izkartojumu
    content.setLayout(new FlowLayout());
    //ieliekam logā pogu
    content.add(poga1);
    content.add(jt);
    content.add(area1);
         //ramim izmeri
    setSize(600,500);
    //pieliekam klausitaju
    poga1.addActionListener(this);
    jt.addActionListener(this);

    //aiversanas operacija
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
  }
public void actionPerformed(ActionEvent a){
    if(a.getSource()== poga1){
        //seit bus darbiba ko veiks poga
        this.metode1();

    }

 }

public void metode1() {
    area1.setText("");
    if (worker != null) {
        worker.cancel(false);
    }
    worker = new SwingWorker() {
        @Override
        protected Integer doInBackground() {

            for (int port = 1; port <= 65535; port++) {  //65535
                try {

                    String input = jt.getText();
                    Socket socket = new Socket();
                    socket.connect(new InetSocketAddress(input, port), 1000);
                    socket.close();
                    area1.append("ports " + port + "atvērts \n");
                    System.out.println("Port " + port + " is open");
                } catch (Exception ex) {}
                return 0;
            }
            worker.execute();
            return null;
        }

    };
}

public static void main(String []args) {
    new PortScanner();
}
}

1 个答案:

答案 0 :(得分:2)

该行

return 0;

将始终从方法返回,因此无论port的实际值是什么,都会终止循环。代码只会执行一次。