0
tcp를 통해 메시지를 보내려고합니다. 불행하게도이 작동하지 않습니다 따라서 나는 테스트 목적으로 다음 코드를 만들었습니다bytearray에서 필드 읽기
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"의 종류의 무언가이다. 왜? 내가 잘못 읽고 있니?
감사합니다.
고마워요, 그 :) 나는 DataInputStream이 여기에서 어떻게 도움이 될지 모르지만, String으로 읽는 방법을 제공하지 않으므로 그렇게하지 않습니까? – user1809923
@ user1809923 상당수의 유형의 XXX에 대해'readInt()','readUTF()','readXXX()'를 가지고 있기 때문에 도움이 될 수 있습니다. 'readUTF()'는'writeUTF()'를 써서'String'을 반환합니다. – EJP