UDP
(inherits from Stream and Printable)
This class enables UDP messages to be sent and received.
// EXAMPLE USAGE
SerialLogHandler logHandler;
// UDP Port used for two way communication
unsigned int localPort = 8888;
// An UDP instance to let us send and receive packets over UDP
UDP Udp;
void setup() {
// start the UDP
Udp.begin(localPort);
// Print your device IP Address via serial
Serial.begin(9600);
Log.info("localIP=%s", WiFi.localIP().toString().c_str());
}
void loop() {
// Check if data has been received
if (Udp.parsePacket() > 0) {
// Read first char of data received
char c = Udp.read();
// Ignore other chars
while(Udp.available())
Udp.read();
// Store sender ip and port
IPAddress ipAddress = Udp.remoteIP();
int port = Udp.remotePort();
// Echo back data to sender
Udp.beginPacket(ipAddress, port);
Udp.write(c);
Udp.endPacket();
}
}
Note that UDP does not guarantee that messages are always delivered, or that
they are delivered in the order supplied. In cases where your application
requires a reliable connection, TCPClient is a simpler alternative.
There are two primary ways of working with UDP - buffered operation and unbuffered operation.
buffered operation allows you to read and write packets in small pieces, since the system takes care of allocating the required buffer to hold the entire packet.
- to read a buffered packet, call
parsePacket, then useavailableandreadto retrieve the packet received - to write a buffered packet, optionally call
setBufferto set the maximum size of the packet (the default is 512 bytes), followed bybeginPacket, then as many calls towrite/printas necessary to build the packet contents, followed finally byendto send the packet over the network.
- to read a buffered packet, call
unbuffered operation allows you to read and write entire packets in a single operation - your application is responsible for allocating the buffer to contain the packet to be sent or received over the network.
- to read an unbuffered packet, call
receivePacketwith a buffer to hold the received packet. - to write an unbuffered packet, call
sendPacketwith the packet buffer to send, and the destination address.
- to read an unbuffered packet, call
Cellular Devices (B-Series SoM, Tracker SoM, Tracker One, Boron, E404X, E-Series, and Electron):
On cellular devices, be careful interacting with web hosts with UDP or libraries using UDP. These can use a lot of data in a short period of time.
Direct TCP, UDP, and DNS do not consume Data Operations from your monthly or yearly quota. However, they do use cellular data and could cause you to exceed the monthly data limit for your account.