%% Send and Receive Multicast Data Packets Using the User Datagram Protocol
% This example shows how to send and receive multicast data using udpport.
%% Create udpport Instances
% Create a udpport instance to send the multicast data.

uSender = udpport()

% Create several udpport instances to receive this multicast data. Ensure that all these udpport instances bind to the same LocalPort with EnablePortSharing set to true. In this example, the udpport instances uReceiver1 and uReceiver2 are bound to LocalPort 3030. uReceiver1 is a datagram type udpport instance and uReceiver2 is a byte type udpport instance.

uReceiver1 = udpport("datagram", "LocalPort", 3030, "EnablePortSharing", true)
uReceiver2 = udpport("LocalPort", 3030, "EnablePortSharing", true)

% You can also create the sender and receivers on different MATLAB instances to communicate between multiple MATLAB instances on the same computer.
%
%% Prepare the Multicast Receivers
% Set multicast on for the udpport multicast receivers using the configureMulticast function. Subscribe to the multicast address group "226.0.0.1". When the uSender sends data to this multicast address group, every udpport instance subscribed to this address receives the multicast data.

configureMulticast(uReceiver1, "226.0.0.1");
configureMulticast(uReceiver2, "226.0.0.1");

% This is reflected in the MulticastGroup and EnableMulticast properties.

uReceiver1.MulticastGroup
uReceiver1.EnableMulticast
uReceiver2.MulticastGroup
uReceiver2.EnableMulticast

%
%% Send Multicast Data
% The uSender instance sends "hello" as a string data type to the multicast address group "226.0.0.1" and the port 3030.

write(uSender,"hello","string","226.0.0.1",3030);

%
%% Receive Multicast Data
% Verify that the multicast receivers uReceiver1 and uReceiver2 get the data. Read this data in MATLAB.
% Ensure that the receivers received the multicast packets. uReceiver1 being a datagram type udpport instance receives the data as a datagram. uReceiver2 being a byte type udpport instance receives the data as raw bytes.

uReceiver1Count = uReceiver1.NumDatagramsAvailable
uReceiver2Count = uReceiver2.NumBytesAvailable

% Read the data from the first receiver as a string, specifying the number of datagrams to read.

data1 = read(uReceiver1,uReceiver1Count,"string");

% data1 is a udpport.datagram.Datagram object. View the data received

data1.Data

% Read the data from the second receiver as a string, specifying the number of bytes of data to read.

data2 = read(uReceiver2,uReceiver2Count,"string")

%
%% Unsubscribe and Clear
% Unsubscribe from the multicast address group.

configureMulticast(uReceiver1, "off");
configureMulticast(uReceiver2, "off");

% Clear the udpport instances.

clear uReceiver1
clear uReceiver2
clear uSender

% Copyright 2020 The MathWorks, Inc.
%