TelnetClient不接收任何数据

时间:2016-03-01 15:12:11

标签: android apache-commons-net

我正在尝试使用Aapche Commons Net库在Android中实现telnet连接。我使用该示例构建了AsyncTask,但似乎根本没有收到任何数据。

这是doInBackground的{​​{1}}:

AsyncTask

我想我复制了示例中的所有代码,但我只得到:

protected Long doInBackground(String... strings) {
    publishProgress("Connecting to "+target+"\n");

    try {
        Thread reader = new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream in = tc.getInputStream();
                byte[] buff = new byte[1024];
                int r = 0;
                try {
                    do {
                        r = in.read(buff);
                        if (r > 0) {
                            publishProgress("[R] " + new String(buff, 0, r));
                        }
                    } while (r >= 0);
                } catch (Exception e) {
                    publishProgress(e.getClass()+": "+e.getMessage());
                } finally {
                    publishProgress("\n ++++ Disconnecting from thread.\n");
                    try {
                        tc.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        tc = new TelnetClient();
        TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
        EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
        SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
        try
        {
            tc.addOptionHandler(ttopt);
            tc.addOptionHandler(echoopt);
            tc.addOptionHandler(gaopt);
        }
        catch (InvalidTelnetOptionException e)
        {
            System.err.println("Error registering option handlers: " + e.getMessage());
        }

        tc.connect(target, port);
        tc.registerNotifHandler(act);

        reader.start();

        reader.join();
    } catch (Exception e) {
        publishProgress(e.getClass()+" "+e.getMessage());
    } finally {
        publishProgress("+++ End of AsyncTask");
    }

    return 0L;
}

当我在笔记本电脑上运行示例代码时,它可以工作,我确实从预期的telnet获取Connecting to 192.168.3.101 negcode=1, optcode=24 (this is from the notifhandler) +++ Disconnecting from thread +++ End of AsyncTask

更新如果我在login之后等待1500毫秒,它确实有效。但这非常难看。

1 个答案:

答案 0 :(得分:0)

不要将线程放在AsyncTask的doInBackground中。只需将代码放入其中即可。