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-typeudpport
object. Datagram-typeudpport
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 thewriteline
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 theTimeout
property of theudpport
object.
Check the default ASCII terminator.
u.Terminator
ans = "LF"
Thewriteline
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 theNumBytesAvailable
property.
u.NumBytesAvailable
ans = 13
Since theudpport
object is connected to an echo server, the data you write is returned to the object. Read a string of ASCII data. Thereadline
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.
clearuechoudp("off")
See Also
udpport
|echoudp
|readline
|writeline