Tcp 从bytearray读取字段

Tcp 从bytearray读取字段,tcp,inputstream,bytebuffer,Tcp,Inputstream,Bytebuffer,我正在尝试通过tcp发送消息。不幸的是,这不起作用,因此我为测试目的创建了以下代码: 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");

我正在尝试通过tcp发送消息。不幸的是,这不起作用,因此我为测试目的创建了以下代码:

    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();

                    ....
}
不幸的是,我读到的时间戳和文本都是垃圾,有点像“[B@44f39650为什么?我读错了吗

谢谢!

“[B@44f39650“是在字节数组对象上调用
toString()
的结果。您在此处执行的操作:

String timestamp = tmp.toString();
所以不要这样做。如果必须这样做,请使用为此目的提供的字符串构造函数将字节数组转换为
字符串


然而,你真的应该使用
DataOutputStream
DataInputStream
的API来达到这个目的。

谢谢,这很有效:)我不太确定DataInputStream在这里能帮到我什么,因为它也不提供读取字符串的方法,是吗?@user1809923它能帮到你,因为它有
readInt()
readUTF()
readXXX()
用于许多类型的XXX。
readUTF()
返回一个
字符串,前提是您使用
writeUTF()
编写该字符串。