1

我在主类中有这段代码:

IOUtil.readWrite(telnet.getInputStream(), telnet.getOutputStream(),
    System.in, System.out);

这非常有效,因为 System.in 从用户那里获取输入,而 System.out 打印所有输出。

我试图改变这一点,因此 System.in 可以是另一个 InputStream 对象,每次请求输入时从文件中读取一行,并且 System.out 可以是一个将所有输出写入文件的对象。

IOUtil 类如下:

package examples;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.io.Util;

public final class IOUtil
{

public  final static void readWrite(final InputStream remoteInput,
                                   final OutputStream remoteOutput,
                                   final InputStream localInput,
                                   final OutputStream localOutput)
{
    Thread reader, writer;

    reader = new Thread()
             {
                 public void run()
                 {
                     int ch;

                     try
                     {
                         while (!interrupted() && (ch = localInput.read()) != -1)
                         {
                             remoteOutput.write(ch);
                             remoteOutput.flush();
                         }
                     }
                     catch (IOException e)
                     {
                         //e.printStackTrace();
                     }
                 }
             }
             ;

    writer = new Thread()
             {
                 public void run()
                 {
                     try
                     {
                         Util.copyStream(remoteInput, localOutput);                                
                     }
                     catch (IOException e)
                     {
                         e.printStackTrace();
                         System.exit(1);
                     }
                 }
             };


    writer.setPriority(Thread.currentThread().getPriority() + 1);

    writer.start();
    reader.setDaemon(true);
    reader.start();

    try
    {
        writer.join();
        reader.interrupt();
    }
    catch (InterruptedException e)
    {
    }
}
4

1 回答 1

1

要替换 System.out,只需使用FileOutputStream.

对于 System.in 的替换,您可以使用FileInputStream. 这不会一次提供一行输入,但我希望远程 telnet 服务器可以处理提前输入,所以这无关紧要。

如果提前输入确实很重要,那么您遇到了一个难题。telnet 客户端的输入端必须与输出端同步,并等到远程服务器/shell 期待下一行后再发送。

  • IOUtil.readWrite方法(如所写)不这样做。
  • 这样做需要输出端注意命令提示符(或其他东西)并告诉输入端写下一行输入。这很棘手......而且很脆弱,原因如下:
    • 您不确定命令提示符会是什么样子。
    • 其中一个命令可以即时更改命令提示。
    • 命令输出可能看起来像一个 shell 命令提示符。

我简要查看了 telnet 协议,我看不到任何内容表明客户端必须一次发送一行数据。

于 2011-05-15T03:43:17.177 回答