Write and Read ASCII Data over UDP
In this example, write and read ASCII data with a UDP object.
Configure and Connect to the Server
Use an echo server to experiment with the basic functionality of the UDP objects without connecting to an actual device. An echo server is a service that returns to the sender's address and port, the same bytes it receives from the sender.
echoudp("on",4040)
Create a byte-type udpport
object. Datagram-type
udpport
objects do not support communication with ASCII-terminated
data.
u = udpport
u = UDPPort with properties: IPAddressVersion: "IPV4" LocalHost: "0.0.0.0" LocalPort: 53816 NumBytesAvailable: 0 Show all properties, functions
Write ASCII Data
Use the writeline
function to write ASCII data to the server. Write a
string to the echo server.
writeline(u,"Request Time","localhost",4040)
The function suspends MATLAB® execution until all the data is written or a timeout occurs as specified by
the Timeout
property of the udpport
object.
Check the default ASCII terminator.
u.Terminator
ans = "LF"
The writeline
function automatically appends the linefeed (LF)
terminator to "Request Time"
before it is written to the server,
indicating the end of the command.
Read ASCII Data
Confirm the success of the write operation by viewing the
NumBytesAvailable
property.
u.NumBytesAvailable
ans = 13
Since the udpport
object is connected to an echo server, the data you
write is returned to the object. Read a string of ASCII data. The
readline
function reads data until it reaches a terminator, removes the
terminator, and returns the data.
data = readline(u)
data = "Request Time"
Clean Up
When you are finished with the UDP object, clear it and turn off the echo server.
clear u echoudp("off")
See Also
udpport
| echoudp
| readline
| writeline