Basic Workflow to Read and Write Data over UDP
This example shows the basic workflow of text read and write operations with a UDP object connected to a remote instrument.
The instrument used is an echo server on a Linux-based PC. An echo server is a service
available from the operating system that returns (echoes) received data to the sender. The
host name is daqlab11
and the port number is 7
. The host
name is assigned by your network administrator.
Create an instrument object — Create a UDP object associated with
daqlab11
.u = udp('daqlab11',7);
Write and read data — You use the
fprintf
function to write text data to the instrument. For example, write the following string to the echo server.fprintf(u,'Request Time')
UDP sends and receives data in blocks that are called datagrams. Each time you write or read data with a UDP object, you are writing or reading a datagram. For example, the string sent to the echo server constitutes a datagram with 13 bytes — 12 ASCII bytes plus the line feed terminator.
You use the
fscanf
function to read text data from the echo server.fscanf(u) ans = Request Time
The
DatagramTerminateMode
property indicates whether a read operation terminates when a datagram is received. By default,DatagramTerminateMode
ison
and a read operation terminates when a datagram is received. To return multiple datagrams in one read operation, setDatagramTerminateMode
tooff
.The following commands write two datagrams. Note that only the second datagram sends the terminator character.
fprintf(u,'%s','Request Time') fprintf(u,'%s\n','Request Time')
Since
DatagramTerminateMode
isoff
,fscanf
reads across datagram boundaries until the terminator character is received.u.DatagramTerminateMode = 'off' data = fscanf(u) data = Request TimeRequest Time
Disconnect and clean up — When you no longer need
u
, you should disconnect it from the host, and remove it from memory and from the MATLAB® workspace.fclose(u) delete(u) clear u
Note
UDP ports can be shared by other applications to allow for multiple applications to
listen to the UDP datagrams on that port. This allows for the ability to listen to UDP
broadcasts on the same local port number in both MATLAB and other applications. You can enable and disable this capability with a new
property of the UDP object called EnablePortSharing
. See Enable Port Sharing over UDP.