MATLAB: Reading UDP from top of buffer

input bufferInstrument Control Toolboxsocket bufferudp

I'm receiving UDP from another machine with the Instrument Toolbox UDP instrument. The objective is to have a timestamp from the sender act as a trigger in Matlab for a camera attached to my Windows PC, so that I can later sync the camera feed with the sender's other data (taking manually into account the latency of sending the message).
However, if the sender sends these timestamps very quickly (1000 Hz), I run into the problem that the datagrams get buffered somewhere, and if left to it the buffer grows over time as Matlab reads slower than the sender sends. Changing the UDP instrument's InputBufferSize doesn't help, as in my limited understanding that is only Matlab's own buffer, and the datagrams get queued somewhere in the OS's network stack. Looking with Wireshark, I see the latest datagrams coming from the sender, so there is some way to read these latest timestamps that I can't get to with Matlab.
Is there a way in Matlab to read the latest datagrams coming into my computer, instead of a FIFO approach? Or a way to make the socket's buffer smaller? I don't care if some or even most datagrams get discarded, as I only need the ones that Matlab is quick enough to read close to real time.
I realize changing the sender's speed would help, but this might still become an issue later.

Best Answer

Exploring this further, the problem is not with Matlab but with the general approach. I found out the mindset of using the UDP first-in-first-out socket queue like a last-in-first-out stack is approaching the problem in a way UDP sockets are not meant to be used, regardless of the programming language. See https://stackoverflow.com/questions/3458385/how-to-make-a-udp-socket-replace-old-messages-not-yet-recvd-when-new-arrive.
The "correct" way of solving this seems to be reading the socket asynchronously while doing other (slower) things with the sender, and implementing your own input buffer in Matlab, to which you can save incoming data with a callback function. Since I only want a single timestamp, I have a "buffer" of only one double-type variable, which I modify in the callback function. The Instrument Toolbox's UDP object has a UserData property that is handy for using with the callback, since it does not return a value.
% Set up UDP object 'u' in the usual way before this line
u.ReadAsyncMode = 'continuous';
u.DatagramReceivedFcn = @callbackFcn;
fopen(u);
while true
pause(1) % Placeholder for doing something else here
disp(u.UserData)
end
function callbackFcn(src, event) % 'src' is the udp object itself
src.UserData=fread(src, src.InputDatagramPacketSize, 'double');
end