简体   繁体   中英

UDP socket Datagram receive packet 2x to get full message

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.

If you write 40 bytes, you should receive 40 bytes. If you write 40 bytes and your buffer is only 20, then you'll lose 20 bytes.

Q: So why not make your buffer 256 bytes (for example), and read whatever you get?

Q: If you need the "message" to arrive in two parts ... then why not just send two messages?

UDP isn't designed for variable length reads - each read() [or recv() ] will correspond to a single write() [or send() ] 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM