%% Tune the UDP Port Number in MATLAB
% The local IP port number of the dsp.UDPReceiver object and the remote IP port number of the dsp.UDPSender object are tunable in the generated code. Generate a MEX file from the receiver function which contains the algorithm to receive sine wave data over a UDP network. Change the remote IP port number of the UDP receiver without regenerating the MEX file. Verify the number of bytes sent and received over the network.
% Note: This example runs only in R2017a or later.
% The input to the receiver function is the local IP port number of the dsp.UDPReceiver System object™. The output of this function is the number of bytes received from the UDP network.

type receiver

%
% The dsp.UDPSender object with remoteIPPort number set to 65000 sends the data over the UDP network. The dsp.UDPReceiver object with LocalIPPort number set to 65000 receives the data from the UDP network. The data is a sine wave containing 250 samples per frame.

portnumber = 65000;
udpSend = dsp.UDPSender('RemoteIPPort',portnumber);
sine = dsp.SineWave('SamplesPerFrame',250);

bytesSent = 0;
bytesReceived = 0;
dataLength = 250;

for i = 1:10
dataSent = sine();
bytesSent = bytesSent + dataLength;
udpSend(dataSent);
bytesReceived = bytesReceived + receiver(portnumber);
end
fprintf('Number of bytes sent: %d', bytesSent);
fprintf('Number of bytes received: %d', bytesReceived);

%
% The data is sent and received successfully over the UDP network. The initial data is dropped due to overhead.
%
% Generate a MEX file from the receiver.m function.

codegen receiver -args {65000}

%
% Release the sender and change the RemoteIPPort number to 25000. The LocalIPPort number of the receiver continues to be 65000. Since the port numbers are different, the data is not transmitted successfully.

release(udpSend)
portnumberTwo = 25000;
udpSend.RemoteIPPort = portnumberTwo; 
bytesReceived = 0;
bytesSent = 0;
for i = 1:10
dataSent = sine();
bytesSent = bytesSent + dataLength;
udpSend(dataSent);
bytesReceived = bytesReceived + receiver_mex(portnumber);
end
fprintf('Number of bytes sent: %d', bytesSent);
fprintf('Number of bytes received: %d', bytesReceived);

%
% Clear the MEX file and change the local IP port number of the receiver to 25000. Clearing the MEX enables the receiver port number to change without having to regenerate the MEX. The port numbers of the sender and receiver match. Verify if the data is transmitted successfully.

clear mex %#ok
bytesReceived = 0;
bytesSent = 0;
for i = 1:10
dataSent = sine();
bytesSent = bytesSent + dataLength;
udpSend(dataSent);
bytesReceived = bytesReceived + receiver_mex(portnumberTwo);
end
fprintf('Number of bytes sent: %d', bytesSent);
fprintf('Number of bytes received: %d', bytesReceived);

%
% The data is transmitted successfully over the UDP network. The initial data is dropped due to overhead.
% Copyright 2012 The MathWorks, Inc.