Efficient way to implement this UDP protocol for loopback IP

조회 수: 7 (최근 30일)
Bandar
Bandar 2021년 7월 24일
댓글: Bandar 2021년 7월 25일
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?

채택된 답변

Walter Roberson
Walter Roberson 2021년 7월 24일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Downloads에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by