2011-09-21 70 views
2

我想通过telnet与Windows服务器中的应用程序进行交互,因此我使用TelnetClient()方法。我可以使用System.in.read()交互(发送命令和检索结果),但是我想要的是这个程序自动运行而不使用任何键盘输入。所以,我的问题是,为什么System.in.read()工作,但ByteArrayInputStream不?为什么ByteArrayInputStream不会返回预期的结果?

这是我到目前为止的代码:

public class telnetExample2 implements Runnable, TelnetNotificationHandler{ 
static TelnetClient tc = null; 
public static void main (String args[]) throws IOException, InterruptedException{ 
    tc = new TelnetClient(); 
    while (true){ 
    try{ 
    tc.connect("192.168.1.13", 8999); 
    } 
    catch (SocketException ex){ 
     Logger.getLogger(telnetExample2.class.getName()).log(Level.SEVERE, null,ex); 
    } 
    Thread reader = mew Thread(new telnetExample2()); 
    tc.registerNotifHandler(new telnetExample2()); 
    String command = "getversion"; //this is the command i would like to write 
    OutputStream os = tc.getOutputStream(); 
    InputStream is = new ByteArrayInputStream(command.getBytes("UTF-8")); //i'm using UTF-8 charset encoding here 
    byte[] buff = new byte[1024]; 
    int ret_read = 0; 
    do{ 
    ret_read = is.read(buff); 
    os.write(buff, 0, 10) 
    os.flush(); 
    while(ret_read>=0); 
    } 
} 

public void run(){ 
InputStream instr = tc.getInputStream(); 
try{ 
    byte[] buff = new byte[1024]; 
    int ret_read = 0; 
    do{ 
    ret_read = instr.read(buff); 
    if(ret_read >0){ 
    System.out.print(new String(nuff, 0, ret_read)); 
    } 
    while(ret_read>=0);} 
    catch(Exception e){ 
    System.err.println("Exception while reading socket:" + e.getMessage()); 
    } 
} 

public void receiveNegotiation(int i, int ii){ 
throw new UnsupportedOperationException("Not supported"); 
} 
} 
+2

在将命令复制到输出流的代码中,存在逻辑错误。 os.write(buff,0,10)必须是os.write(buff,0,ret_read) –

+0

你还没有说你在观察什么。请阅读http://tinyurl.com/so-hints –

回答

6
InputStream is = new ByteArrayInputStream(command.getBytes("UTF-8")); //i'm using UTF-8 charset encoding here 
byte[] buff = new byte[1024]; 
int ret_read = 0; 
do{ 
ret_read = is.read(buff); 
os.write(buff, 0, 10) 
os.flush(); 
while(ret_read>=0); 
} 

可以减少这些9号线不工作,os.write(command.getBytes("UTF-8"));哪些呢。

为什么你认为最多可以读取1024个字节到缓冲区,然后只写出其中的前10个是有用的,这是一个谜。

+0

+1:那是我想知道的。 ;) –