【发布时间】:2019-06-05 11:12:47
【问题描述】:
我刚开始使用 Java,并试图通过 TCP/IP 与外部设备进行通信。我向设备发送命令并收到适当的响应。
到目前为止,如果我在发送和接收之间等待 1 秒,则通信正常。让我恼火的是接收到的数据比预期的长了 7 个字节。在响应之前总是字节 2A 48 45 4C 4C 4F 2A。
我希望有人能告诉我为什么这是错的,如果我做错了什么。
Socket socket = new Socket("192.168.0.40", 80);
byte[] ba_sendBuffer = new byte[1024];
// fill sendBuffer
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(ba_sendBuffer.length); // write length of the message
dOut.write(ba_sendBuffer); // write the message
dOut.flush();
// Wait for device
Thread.sleep(1000);
byte[] ba_responseBuffer = new byte[0];
if (socket.isConnected())
{
InputStream inFromServer = socket.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
synchronized (in)
{
int length = in.available();
ba_responseBuffer = new byte[length];
in.readFully(ba_responseBuffer);
}
// ba_responseBuffer - the first 7 bytes are not expected
// work with the response
}
【问题讨论】:
-
2A 48 45 4C 4C 4F 2A是 ASCII 格式的*HELLO*。我猜你忘记了一些测试代码...... -
你在消息前发送缓冲区的长度,或许有答案。
-
@DenysSéguret:HELLO 你说得对,但为什么呢?我的代码不包含“你好”这个词。我用Wireshark分析了数据,发现设备的响应不包含* HELLO *。
-
@MladenSavić:命令无效。
-
我刚收到一个同事的答复,她真的很傻。我通过WIFI连接到设备,打开连接时模块总是发送* HELLO *。问题已解决。非常感谢您的帮助。
标签: java sockets datainputstream