gpt4 book ai didi

java - 为什么 ByteArrayInputStream 没有返回预期的结果?

转载 作者:行者123 更新时间:2023-11-30 05:56:10 27 4
gpt4 key购买 nike

我正在尝试通过 telnet 与 Windows 服务器中的应用程序进行交互,因此我使用的是 TelnetClient() 方法。我可以使用 System.in.read() 进行交互(发送命令和检索结果),但是我希望这个程序在不使用任何键盘输入的情况下自动运行。所以,我的问题是,为什么 System.in.read() 有效,而 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 = new 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");
}
}

最佳答案

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 个字节是可行的,这是一个谜。

关于java - 为什么 ByteArrayInputStream 没有返回预期的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7498067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com