简体   繁体   中英

Cannot read line break/carriage return from socket response

I am sending setup commands to a TP-LINK wireless router through a telnet connection:

Trying 1.2.3.4...
Connected to 1.2.3.4.
Escape character is '^]'.
*HELLO*$$$
CMD
factory RESET
factory RESET

Set Factory Defaults
<4.00> set sys autoconn 0
set sys autoconn 0

AOK
<4.00>
...

I have a PHP code that performs the sending of commands and gets the response using sockets:

socket_write($socket, "factory RESET\r"); // send command
$response = socket_read($socket, 256); // get response

PHP works fine. The $response variable contains:

factory RESET

Set Factory Defaults

But using the Java I have problems. Using a BufferedReader object to read response, I can get the first line content. but I can not get the following lines:

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// ...
bw.write("factory RESET");
bw.newLine();
bw.flush();
// ...
StringBuilder sb = new StringBuilder();

String s;
while ((s = br.readLine()) != null) {
   sb.append(s);
}

I can get the first line content, but the second reading don't proceed and don't raise exception... If I use the read function, only the first row is returned:

char[] buffer = new char[256];
br.read(buffer, 0, 256);
String response = new String(buffer); // response is "factory RESET"

What is the problem?

  1. Your PHP code execute two reads. Your Java code attempts to read until end of stream, which only happens when the peer closes the connection. Do a single read.

  2. The line separator in the Telnet protocol is defined as \\r\\n , unless you're using binary mode, which you aren't. Not as \\r or whatever BufferedWriter may do on your platform.

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