Since I had the opportunity to implement Socket communication in practice for the first time, I will make a note of my impressions and technology used. When I was studying by myself in the past, I didn't get it right, but I was able to experience it by looking at the data specifications and implementing it.
It seems that there are two types, server socket and client socket, but this time I used only the client socket. The impression was that there was a Java Socket API, but in the end, it was a byte stream exchange. The data specification also said something like "Data A: xxx to 4 bytes".
I referred to the following articles. @ Hyman1993 Summary of Java communication API (1) How to use Socket @Gin About TCP stream communication breaks / breaks
There was a statement in the design document that "data is stored in little endian". For me, who is a beginner of Socket communication, it was a mess.
I referred to the article by @mikanbako. Byte order must be reset to duplicate ByteBuffer
--In order to process the read data, it is necessary to convert each byte array specified in the data specifications into a numerical value or a character string. --If the data is little endian, you need to specify the little endian when replicating to the ByteBuffer class. Ex. byteBuffer.order(ByteOrder.LITTLE_ENDIAN)
LittleEndianSample.java
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class LittleEndianSample {
public static final void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(Short.BYTES);
//Little endian 16-bit integer. The low byte is 0x11 and the high byte is 0x22.
buffer.order(ByteOrder.LITTLE_ENDIAN)
.put((byte) 0x11)
.put((byte) 0x22)
.rewind();
System.out.printf("0x%x\n", buffer.getShort());
}
}
Recommended Posts