I am building an experimental game server in Java.
Client sends:
length: 22\r\n
playerId: 0\r\n
\r\n\r\n
this is a test message
Java code to receive message:
String message = "";
byte[] buf = new byte[20];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socketServer.receive(packet);
message += new String(buf, "UTF8");
buf = new byte[20];
packet = new DatagramPacket(buf, buf.length);
socketServer.receive(packet);
message += new String(buf, "UTF8");
This doesn’t receive 40 bytes of the message sent by the client, it receives 20 bytes and on the second socketServer.receive(packet) it hangs for a new message.
Reason by def:
This method blocks until a datagram is received. The length field of
the datagram packet object contains the length of the received
message. If the message is longer than the packet’s length, the
message is truncated.
I need to be able to read 20 bytes of the message and another 20 bytes of the message. How can this be achieved?
I need this because I’m not sure how long the message will be. I want something like this:
String message = "";
while (!message.contains("\r\n\r\n")) { //"\r\n\r\n" marks end of message
byte[] buf = new byte[20];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socketServer.receive(packet);
message += new String(buf, "UTF8");
}
This gets full message assuming message ends with \r\n\r\n.
It needs to be done over the UDP protocol. I am new to sockets in Java but I assume there is something for this, just cannot find it. Thanks in advance.
UDP isn’t designed for variable length reads – each
read()[orrecv()] will correspond to a singlewrite()[orsend()] on the server.If you only read 20 bytes of a 40 byte packet the remaining bytes will be discarded.
You need to create a buffer large enough to receive the entire packet (max 65536 bytes if your network handles fragmentation properly) and then read the entire packet in one go.
The API will tell you how many bytes were actually received – you should consider checking that against the value encoded within the packet to ensure that you did receive the entire packet.