Note that there are some explanatory texts on larger screens.

plurals
  1. POUDP socket Datagram receive packet 2x to get full message
    text
    copied!<p>I am building an experimental game server in <code>Java</code>.</p> <p>Client sends:</p> <pre><code>length: 22\r\n playerId: 0\r\n \r\n\r\n this is a test message </code></pre> <p><code>Java</code> code to receive message:</p> <pre><code>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"); </code></pre> <p>This doesn't receive 40 bytes of the message sent by the client, it receives 20 bytes and on the second <code>socketServer.receive(packet)</code> it hangs for a new message.</p> <p>Reason by def:</p> <blockquote> <p>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.</p> </blockquote> <p>I need to be able to read 20 bytes of the message and another 20 bytes of the message. How can this be achieved?</p> <p>I need this because I'm not sure how long the message will be. I want something like this:</p> <pre><code>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"); } </code></pre> <p>This gets full message assuming message ends with <code>\r\n\r\n</code>.</p> <p>It needs to be done over the <code>UDP</code> protocol. I am new to sockets in <code>Java</code> but I assume there is something for this, just cannot find it. Thanks in advance. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload