【问题标题】:TelnetClient receives no dataTelnetClient 没有收到数据
【发布时间】:2016-06-14 02:00:24
【问题描述】:

我正在尝试使用 Aapche Commons Net 库在 Android 中实现 telnet 连接。我用例子构建了一个AsyncTask,但是好像根本没有收到数据。

这是我的AsyncTaskdoInBackground

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;
}

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

Connecting to 192.168.3.101
negcode=1, optcode=24 (this is from the notifhandler)
+++ Disconnecting from thread
+++ End of AsyncTask

当我在笔记本电脑上运行示例代码时,它可以工作,我确实按预期从 telnet 获得了 login

更新如果我在tc.connect() 之后等待 1500 毫秒,它确实有效。但这是一个非常丑陋的 hack。

【问题讨论】:

    标签: android apache-commons-net


    【解决方案1】:

    不要将线程放在 AsyncTask 的 doInBackground 中。把代码放进去就行了。

    【讨论】:

    • 是的,我知道。这是一些从示例中复制代码的实验。我在另一部分也有同样的结果。
    猜你喜欢
    • 2012-10-19
    • 2021-05-12
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多