【问题标题】:Java socket receives more bytes than expectedJava 套接字接收的字节数比预期的多
【发布时间】: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


【解决方案1】:

问题解决了。我刚刚收到一位同事的答复。我通过WIFI连接到设备,打开连接时模块总是发送* HELLO *。问题已解决。

【讨论】:

  • ...一个同事,她真的很蠢...她的 Stackoverlow 用户名是什么?
  • 我猜你的意思是问题很蹩脚,而不是你的同事很愚蠢xD
  • @SvetlinZarev:对不起。哟是对的。问题是愚蠢/蹩脚的,不是我的同事。 “语言精度”;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2016-01-27
  • 1970-01-01
  • 2013-09-08
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多