Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NIO DatagramChannel will I need to handle partially read/written packets?

When using SocketChannel, you need to retain read and write buffers to handle partial writes and reads.

I have a nagging suspicion that it might not be needed when using a DatagramChannel, but info is scarce.

What is the story?

Should I call (non-blocking) receive(ByteBuffer) repeatedly until I get a null back to read all waiting datagrams?

When sending in non-blocking mode, can I rely on send(ByteBuffer, SocketAddress) to either send the the whole buffer or rejecting it entirely, or do I need to possibly keep partially written buffers?

like image 510
Nuoji Avatar asked Dec 29 '25 07:12

Nuoji


1 Answers

Every read of a Datagram is the entire datagram, nothing more, nothing less. There's a hint that this is the case in the description of java.nio.DatagramChannel.read:

If there are more bytes in the datagram than remain in the given buffers then the remainder of the datagram is silently discarded

When you're dealing with a SocketChannel, it's a message stream; there's no guarantee how much or how little data you'll get on each read, as TCP is reassembling separate packets to recreate the message from the other side. But for UDP (which is what you're reading with the DatagramChannel) each packet is its own atomic message.

like image 53
Jared Oberhaus Avatar answered Dec 31 '25 20:12

Jared Oberhaus