简体   繁体   中英

Can't receive any response from Telnet server on Android

I need to implement a simple telnet client on Android. I tried to use org.apache.commons.net.telnet.TelnetClient class:

TelnetClient telnet = new TelnetClient();

telnet.connect( "localhost", PORT);

InputStream inStream = telnet.getInputStream();
PrintStream outStream = new PrintStream( telnet.getOutputStream());

outStream.println( COMMAND);
outStream.flush();

int ch = 0;
while( ( ch = inStream.read()) != -1) {
    log("Respose:" + ch);
}

but inStream.read() blocks.

At the same time I can get the response from the server using a telent app from Market.

Any idea what I'm doing wrong?

i am using apache telnet client and i had the same problem. reason is telnet server is streaming response and there is no END token. something like end-of-line ..etc.

so You will keep getting bytes and if there is no incoming byte, then it will block at read() method.

So i used StringBuilder to keep all incoming bytes as chars and also keep track of specific string (":/ #") which is the always at the end of transmitted stream (for telnet connection). Even in first connection.

This is a part of code i used.

StringBuilder builder = new StringBuilder();
TelnetClient telnet = new TelnetClient();
telnet.connect("127.0.0.1", 23);
outstr = telnet.getOutputStream();
instr = telnet.getInputStream();
int cnt =0;
    while(isConnected){
        if(builder.toString().endsWith(":/ #")){
                cnt++;
                if(cnt==2){
                    Log.i("DATA : ", builder.toString());
                    builder.delete(0, builder.length());
                    cnt=1;
                }
        }
        builder.append((char)instr.read());

    }

if you noticed that builder is cleaned if counter "cnt" reaches 2. and counter is set to 1. "cnt" shows the number of token (":/ #") i choose to define end of stream.

First connection will give the first token but to get the end you need counter to decide if it is the end token. that is why i used counter.

Suggestion : keep listening code on different thread and command sending code in another one. (eventually you will, because of android, you need to handle networkOnMainThread ..etc.)

Not : Code above is not a full copy. but it is a simplified part of working one. Full version seperates listen , command send and exception handling with distributed form.

Does it block after some chars ? Because you ask it to stop reading only when the end of the inputStream is reached.

I don't know about telnet protocole, but it seems to me you should read lines from the input stream, using a BufferedReader for instance.And as soon as a line is read from server, process it.

我认为不要使用“ localhost”,而要使用该特定计算机的IP地址。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM