MATLAB: Does UDP read not return a full datagram

ictInstrument Control Toolboxudp

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

Best Answer

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: