Broadcast User Datagram Protocol Data Packets
This example shows how to send and receive broadcast datagram packets using the udpport
function.
Create udpport Broadcaster
Create a datagram type udpport
broadcaster instance
uBroadcaster = udpport("datagram")
uBroadcaster = UDPPort with properties: IPAddressVersion: "IPV4" LocalHost: "0.0.0.0" LocalPort: 59646 NumDatagramsAvailable: 0 Show all properties, functions
Set the EnableBroadcast
property to allow for broadcasting.
uBroadcaster.EnableBroadcast = true;
Create udpport Receivers
Create udpport
instances that receive the broadcast data. These receivers are bound to LocalPort
2020 with EnablePortSharing
enabled so that multiple udpport
objects can bind to the same socket. uReceiver1
is a byte type udpport
instance and uReceiver2
is a datagram type udpport
instance.
uReceiver1 = udpport("byte","LocalPort",2020,"EnablePortSharing",true)
uReceiver1 = UDPPort with properties: IPAddressVersion: "IPV4" LocalHost: "0.0.0.0" LocalPort: 2020 NumBytesAvailable: 0 Show all properties, functions
uReceiver2 = udpport("datagram", "LocalPort",2020,"EnablePortSharing",true)
uReceiver2 = UDPPort with properties: IPAddressVersion: "IPV4" LocalHost: "0.0.0.0" LocalPort: 2020 NumDatagramsAvailable: 0 Show all properties, functions
Send Broadcast Data
The broadcaster sends data to the broadcast address "192.168.255.255" and the port 2020, to which the receivers are bound. In this example, the broadcast address is "192.168.255.255", which is determined by the network address and the subnet mask. This address will be different on your computer.
Write the data 1:5, specified as uint8 data.
write(uBroadcaster,1:5,"uint8","192.168.255.255",2020);
Receive Broadcast Data
Now that the broadcaster has sent the data, the receivers receive these data packets.
Verify that the value of the NumBytesAvailable
property of uReceiver1
is 5, indicating that five bytes of data was received.
uReceiver1Count = uReceiver1.NumBytesAvailable
uReceiver1Count = 5
Verify that the value of the NumDatagramsAvailable
property of uReceiver2
is 1, indicating that one datagram was received.
uReceiver2Count = uReceiver2.NumDatagramsAvailable
uReceiver2Count = 1
Read the 5 bytes of data from uReceiver1
.
data1 = read(uReceiver1,uReceiver1Count,"uint8")
data1 = 1×5
1 2 3 4 5
Read the 1 datagram received on uReceiver2.
data2 = read(uReceiver2,uReceiver2Count,"uint8");
data2
is a udpport.datagram.Datagram
object. View the data received.
data2.Data
ans = 1×5
1 2 3 4 5
Clear Instances
Clear the udpport
broadcaster and receiver instances.
clear uBroadcaster clear uReceiver1 clear uReceiver2