MATLAB Answers

Why does UDP read not return a full datagram?

6 views (last 30 days)
I'm sending and receiving UDP datagrams between MATLAB sessions. The sender sends 1024-byte datagrams, and the receiver tries to read a full datagram at a time, but it is reporting that it is only reading 256 bytes. How can I make it read the full datagram?
Sender:
u1 = udp('localhost', 'RemotePort', 9090);
udps.OutputBufferSize = 1024*100;
for i=1:100
packet = rand(1, 1024);
fwrite(u1, packet, 'int16');
end
Receiver:
u2 = udp('localhost', 'LocalPort', 9090);
u2.InputBufferSize = 1024*100;
u2.DatagramReceivedFcn = @myFunc;
function myFunc(obj, event)
data = fread(obj, obj.InputDatagramPacketSize, 'int16');
fprintf('%d bytes received', length(data));
end

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 7 Apr 2020
The 256 value that that is observed here is actually the number of values read from the UDP object, not the number of bytes read. Since the bytes being read were interpreted as 'int16' values, each value being read consisted of 2 bytes (16 bits), so we are actually reading 2*256 = 512 bytes from the UDP object. Note that this can also be applied to the UDP sender: we are writing 1024 values each represented by 2-bytes, so our write operation is actually writing 2048 bytes.
The reason we are reading only 512 bytes instead of the expected 1024-byte-long datagram we expected is because the default OutputDatagramPacketSize is 512-bytes, so the UDP sender is only sending 512-byte datagrams. If we change this property:
>> udps.OutputDatagramPacketSize = 1024;
We will be able to read the expected 1024-byte packets.
For more information on how read and write operations work in the UDP interface, refer to the following documentation:

  0 Comments

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Tags

Products


Release

R2019b

Translated by