Pb. receiving UDP datagrams

G

Guest

Hi,

I receive a continuous flow of UDP datagrams on my PC that I would like
to process in a Java program. I wrote the following piece of code but I
can't get any datagram (the .receive() function blocks forever). I
checked with a network sniffer - Ethereal/WireShark - and I could
verify the presence of a continuous UDP flow with valid UDP datagram
headers (destination port: 8081; checksum = 0 (none)).

Could someone help me finding out what I'm doint wrong?

Eric

PS: The piece of code:

public final class UDPClient {
private static final Logger logger = Logger.getRootLogger();
static byte[] buffer = new byte[65507];

public static void main(String[] args) {
try {
DatagramSocket ds;
ds = new DatagramSocket(8081);
DatagramPacket dpi;
dpi = new DatagramPacket(new byte[512], 512);
while(true) {
ds.receive(dpi);
logger.info("UDP datagram received from " +
dpi.getAddress() + ":" + dpi.getPort());
}
} // end try
catch (Exception e) {
System.err.println(e);
} // end catch
}
}
 
C

Chris Uppal

DatagramSocket ds;
ds = new DatagramSocket(8081);
DatagramPacket dpi;
dpi = new DatagramPacket(new byte[512], 512);
while(true) {
ds.receive(dpi);

Comparing this with some working code of my own, the only difference I can see
is that I set the size of the DatagramPacket explicitly before each receive().
My code reads:

DatagramSocket socket = new DatagramSocket(PORT);
DatagramPacket packet = new DatagramPacket(
new byte[BUFFER_SIZE],
BUFFER_SIZE);
for (;;)
{
packet.setLength(BUFFER_SIZE);
socket.receive(packet);
...

The Java network stuff treats the length of the packet as separate from the
length of the buffer which is used to send/receive it.

-- chris
 
G

Gordon Beaton

The Java network stuff treats the length of the packet as separate
from the length of the buffer which is used to send/receive it.

Unfortunately the length associated with the DatagramPacket is used
for two purposes: to tell receive() how much you want to receive, and
to find out how much was actually received.

So if you attempt to reuse a DatagramPacket but forget to call
setLength() before receive(), you will find that your receives can
only get shorter as a result, never longer, until you reach 0.

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top