0

I am trying to send a message via tcp. Unfortunately that does not work and hence I have created the following code for test purposes:

    public void sendQuestion(String text) {
        // Set timestamp.
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        TimeZone tz = TimeZone.getTimeZone("GMT+01:00");
        df.setTimeZone(tz);
        String date = df.format(new Date());

        byte[] dateStr = date.getBytes();

        // Set payload.
        String payloadTemp = date + text;
        byte[] payload = payloadTemp.getBytes();

        // Send the payload.
        clientOutputThread.send(1, payload);

           ....
    }   


 public void send(byte type, byte[] payload) {
            // Calculate and set size of message.
            ByteBuffer bufferTemp = ByteBuffer.allocate(4);
            bufferTemp.order(ByteOrder.BIG_ENDIAN);
            byte[] payloadSize = bufferTemp.putInt(payload.length).array();

            byte[] buffer = new byte[5 + payload.length];

            System.arraycopy(payloadSize, 0, buffer, 0, 4);
            System.arraycopy(payload, 0, buffer, 5, payload.length);

            // Set message type.
            buffer[4] = type;

            // TEST: Try reading values again

            ByteBuffer bb = ByteBuffer.wrap(buffer);  
            // get all the fields:
            int payload2 = bb.getInt(0);  // bytes 0-3
                                         // byte 4 is the type
            byte[] tmp = new byte[19]; // date is 19 bytes
            bb.position(5);
            bb.get(tmp); 
            String timestamp = tmp.toString();
            byte[] tmp2 = new byte[payload2-19];
            bb.get(tmp2); // text
            String text = tmp2.toString();

                    ....
}

Unfortunately, what I read as timestamp and text is rubbish, something of the sort of "[B@44f39650". Why? Am I reading wrong?

Thank you!

user1809923
  • 1,235
  • 3
  • 12
  • 27

1 Answers1

0

"[B@44f39650" is the result of calling toString() on an object which is a byte array. Which you are doing here:

String timestamp = tmp.toString();

So don't do that. Convert the byte array to a String, if you must do that at all, using the String constructors provided for the purposes.

However you should really be using the API of DataOutputStream and DataInputStream for this purpose.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • thanks, that worked :) Not so sure how DataInputStream can help me here though, since that does not provide a method to read in a String either, does it? – user1809923 Dec 03 '12 at 12:25
  • @user1809923 It can help you because it has `readInt()`, `readUTF()`, `readXXX()` for quite a few types of XXX. `readUTF()` returns a `String`, provided you wrote it with `writeUTF()`. – user207421 Dec 04 '12 at 04:01