Search code examples
javasocketsdatainputstream

Java socket receives more bytes than expected


I have just started with Java and am trying to communicate with an external device via TCP/IP. I send a command to the device and receive an appropriate response.

The communication works so far, if I wait 1 second between sending and receiving. What irritates me is that the received data is 7 bytes longer than expected. Before the response are always the bytes 2A 48 45 4C 4C 4F 2A.

I hope that someone can tell me why this is wrong and if I am doing something wrong.

    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
    }

Solution

  • The problem is solved. I have just received the answer from a colleague. I am connected to the device via WIFI and the module always sends a * HELLO * when opening the connection. Question has been settled.