我正在使用Android(Java)中的套接字编写与Telnet服务器连接的应用程序。它每2秒向服务器发送一个命令,服务器回复该命令。当我从服务器收到输出时,读者似乎不断将其添加到过去收到的数据中。很明显,BufferedReader没有“冲洗”。选项,我在网上找到的主题到目前为止似乎并不适用于这种情况。有谁愿意帮我解决这个问题?我现在坚持了一个星期。
runthread = new Thread(new Runnable() {
@Override
public void run() {
String remoteip = "192.168.1.39";
int remoteport = 4212;
Socket telnet = null;
try {
telnet = new Socket(remoteip, remoteport);
}catch(UnknownHostException e){
System.out.println("Exception telnet: " + e.getMessage());
}catch(IOException e){
System.out.println("Exception IO: " + e.getMessage());
}
try {
telnet.setKeepAlive(true);
}catch(Exception e){
System.out.println("Exception keepalive: " + e.getMessage());
return;
}
final BufferedReader reader;
final PrintWriter writer;
try {
reader = new BufferedReader(new InputStreamReader(telnet.getInputStream()));
writer = new PrintWriter(telnet.getOutputStream());
}catch(Exception e){
System.out.println("Exception reader/writer: " + e.getMessage());
return;
}
char[] buffer = new char[4096]; // Read 4K characters at a time
int len; // How many chars read each time
try {
while ((len = reader.read(buffer)) != -1 ) {
String readchar = new String(buffer, 0, len);
System.out.println(readchar); //THIS IS WHERE IT PRINTS THE OUTPUT
stateTimer = new Timer();
stateTimer.schedule(new TimerTask() {
@Override
public void run() {
writer.print("status\n"); //ASK FOR SOME OUTPUT EVERY 2 SECONDS
writer.flush();
}
}, 0, 2000);
}
}catch (Exception e){
System.out.println("while() exception:" + e.getMessage());
}
}
});
runthread.start();