Efficient way to implement this UDP protocol for loopback IP

2 views (last 30 days)
I'm working on a project where I need to send data via UDP protocol from one PC to another. Currently, I'm using two Matlab sessions for this purpose. See the following codes. The first session is
% Matlab Session 1 (Local Side)
clear all
clc
t=0:0.01:10;
u1 = udpport("LocalPort",8844);
pause(3)
for i = 1:numel(t)
v = 2;
w = .3;
input = num2str(v) + " " + num2str(w);
% send control input to remote side
write(u1,input,"string","HostName",8866);
flush(u1);
pause(.25)
end
The second session is
% Matlab Session 2 ( Remote Side )
u2 = udpport("LocalPort",8866,"LocalHost","HostName");
while true
if u2.NumBytesAvailable ~= 0
data = read(obj.u2,obj.u2.NumBytesAvailable,"string")
inputStr = split(data," ");
input = str2double(inputStr);
v = input(1);
w = input(2);
flush(u2);
end
end
The codes work but sometimes, at the remote side, instead of receiving two strings, it receives more. Flushing out the buffer doesn't solve the problem. How to fix and ameliorate the codes?

Accepted Answer

Walter Roberson
Walter Roberson on 24 Jul 2021
udp does not synchronize: is is completely happy to send of 1000 packets from a source in the time before the first of them is processed by the receipient.
You are sending without newline or terminator, but you are reading according to bytes available, and you are asking for all of the bytes that are currently in the buffer. So if the source has sent packet 1 and packet 2, then the NumBytesAvailable includes byte counts for both packets, and your read() asks to read them both together without putting any kind of separation between the two.
If you are not going to send terminators, you should be switching to Datagram mode and asking about NumDatagramsAvailable and read datagrams.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!