Hardware Reference
In-Depth Information
The loop() just calls the listen()
method, which listens for incoming
UDP packets on the same port on
which the Processing sketch broad-
casts.
8
Continued from opposite page.
void loop()
{
listen(query, myPort);
}
8 First, you parse the packet
to get the header items.
Receiving UDP packets is a bit different
than receiving TCP packets. Each
packet contains a header that tells you
who sent it and from what port, kind
of like an envelope. When you receive
a packet, you have to parse out that
data. The parsePacket() method in
the Arduino UDP library does just that.
You can see it in action here. First, you
parsePacket() to separate the header
elements from the message body.
Then, you read the message body byte-
by-byte, just like you've done already
with TCP sockets and serial ports.
void listen(UDP thisUDP, unsigned int thisPort) {
// check to see if there's an incoming packet, and
// parse out the header:
int messageSize = thisUDP.parsePacket();
// if there's a payload, parse it all out:
if (messageSize > 0) {
Serial.print("message received from: ");
// get remote address and port:
IPAddress yourIp = thisUDP.remoteIP();
unsigned int yourPort = thisUDP.remotePort();
for (int thisByte = 0; thisByte < 4; thisByte++) {
Serial.print(yourIp[thisByte], DEC);
Serial.print(".");
}
Serial.println(" on port: " + String(thisPort));
// send the payload out the serial port:
while (thisUDP.available() > 0) {
// read the packet into packetBufffer
int udpByte = thisUDP.read();
Serial.write(udpByte);
}
sendPacket(thisUDP, Ethernet.localIP(), yourIp, yourPort);
}
}
8 Then, you read the rest of
the message body.
8
The sendPacket() method sends a
response packet to whatever address
and port it receives a message from. It
includes its IP address in the body of
the message as an ASCII string.
void sendPacket(UDP thisUDP, IPAddress thisAddress,
IPAddress destAddress, unsigned int destPort) {
// set up a packet to send:
thisUDP.beginPacket(destAddress, destPort);
for (int thisByte = 0; thisByte < 4; thisByte++) {
// send the byte:
thisUDP.print(thisAddress[thisByte], DEC);
thisUDP.print(".");
}
thisUDP.println("Hi there!");
thisUDP.endPacket();
}
You can see that UDP messaging
is different than the socket-based
messaging over TCP. Each message
packet has to be started and ended.
When you beginPacket() , the Ethernet
controller starts saving bytes to send in
its memory; when you endPacket() , it
sends them out.
 
Search WWH ::




Custom Search