简体   繁体   English

无法读取套接字响应中的换行符/回车符

[英]Cannot read line break/carriage return from socket response

I am sending setup commands to a TP-LINK wireless router through a telnet connection: 我正在通过telnet连接将设置命令发送到TP-LINK无线路由器:

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: 我有一个PHP代码,该命令执行命令发送并使用套接字获取响应:

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

PHP works fine. PHP可以正常工作。 The $response variable contains: $response变量包含:

factory RESET

Set Factory Defaults

But using the Java I have problems. 但是使用Java我有问题。 Using a BufferedReader object to read response, I can get the first line content. 使用BufferedReader对象读取响应,可以获取第一行内容。 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: 我可以获得第一行的内容,但是第二次阅读不会继续进行,也不会引发异常...如果使用read函数,则仅返回第一行:

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. 您的PHP代码执行两次读取。 Your Java code attempts to read until end of stream, which only happens when the peer closes the connection. 您的Java代码尝试读取直到流结束,这仅在对等方关闭连接时发生。 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. Telnet协议中的行分隔符定义为\\r\\n ,除非您使用的不是二进制模式。 Not as \\r or whatever BufferedWriter may do on your platform. 不像\\rBufferedWriter在您的平台上可能做的任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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