繁体   English   中英

android项目中的J2ME类

[英]J2ME class in android project

我将端口扫描程序类复制到了我的android项目中,而不更改源代码中的任何内容。 Eclipse没有抱怨代码,但是我的代码似乎在android中无法正常工作。 这是我的全部portscanner代码。

import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class PortScanner {

    private final String ip;
    private final int sPort, ePort, timeout, poolSize;
    private ArrayList<Integer> openPorts = new ArrayList();
    private final ExecutorService es;
    private Collection<Future<?>> futures = new LinkedList<>();


    public PortScanner(String ip, int sPort, int ePort, int timeout, int poolSize) {
        this.ip = ip;
        this.sPort = sPort;
        this.ePort = ePort;
        this.timeout = timeout;
        this.poolSize = poolSize;
        es = Executors.newFixedThreadPool(this.poolSize);

    }

    public ArrayList<Integer> getPorts() {
        return openPorts;
    }

    public void runScanner() {

        for (int startPort = sPort; startPort <= ePort; startPort++) {
            futures.add(es.submit(new Check(ip, startPort, timeout)));
        }

        es.shutdown();

    }

    private class Check implements Runnable { //  BEGININ OF INNER CLASS

        private String ip;
        private int port, timeout;

        private Check(String ip, int port, int timeout) {
            this.ip = ip;
            this.port = port;
            this.timeout = timeout;
        }

        @Override
        public void run() {

            try {
                Socket socket = new Socket();
                socket.connect(new InetSocketAddress(ip, port), timeout);
                socket.close();
                openPorts.add(port);
            } catch (Exception ex) {
            }
        }
    }                                       // END OF INNER CLASS
}

我以几种不同的方式测试了我的代码,并确定只有不正确的是内部类run方法,因为当我手动将一些端口添加到数组列表时,它们会打印,但是当我放置扫描仪时,它们总是返回空的。 相同的端口扫描代码可在桌面上完美运行。 有人知道我在做什么错吗?

不知道这是否是您遇到的问题,但是您正在从多个线程向不是线程安全的ArrayList中添加内容,而没有任何类型的同步。 这将导致行为不稳定。

此外,您不会显示如何以及何时显示此列表的内容。 调用代码无法知道扫描何时结束,因此,如果您在调用runScanner()之后runScanner()询问列表,则很有可能没有任何扫描任务执行完毕。 顺便说一句,如果您从不使用此列表,为什么还要将期货添加到期货列表中?

你检查过例外了吗? 如果在将套接字添加到openPorts之前引发异常,您将获得一个空数组列表。 而且在捕获到异常时您没有打印异常堆栈-当我忘记在异常-catch中打印错误日志时,我也会遇到类似的问题。

        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(ip, port), timeout);
            socket.close();
            openPorts.add(port);
        } catch (Exception ex) {
            //It's better to do something at least print an error log
            ex.printStackTrace();
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM