Reputation: 33
With UDP, if I send two DatagramPackets on one DatagramSocket (let's say first datagram say "ABCD" and the second say "EFGH"), is it theorically possible that my first call to "receive" on the socket give me a DatagramPacket containing "ABCDEFGH"?
In other words, does messages sent with UDP can be grouped into one message and if so, does UDP "remembers" it was several distincts messages in the first place?
Let's assume my client is :
//DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getByName("127.0.0.1");
// Send a first message
String str = "ABCD";
DatagramPacket dp1 = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
ds.send(dp1);
// Send a second message (on the same socket)
str = "EFGH";
DatagramPacket dp2 = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
ds.send(dp2);
ds.close();
}
}
And my server is:
//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
This code may output "ABCD", it may also output "EFGH" (if first message is lost), it may also output nothing at all (if both messages are lost), but can it output "ABCDEFH"?
Upvotes: 0
Views: 35
Reputation: 311052
No. UDP datagrams are received intact and entire, or not at all. Also possibly multiple times, out of order, ... but never coalesced.
Upvotes: 1