Main Content

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-typeudpportobject. Datagram-typeudpportobjects 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 thewritelinefunction 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 theTimeoutproperty of theudpportobject.

Check the default ASCII terminator.

u.Terminator
ans = "LF"

Thewritelinefunction 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 theNumBytesAvailableproperty.

u.NumBytesAvailable
ans = 13

Since theudpportobject is connected to an echo server, the data you write is returned to the object. Read a string of ASCII data. Thereadlinefunction 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

|||

Related Topics