EthernetUDP.read()
描述
读取透过 UDP 接收到的资料。如果没有给参数,会回传待读资料中的第一个资料。
要使用 read()
前必须先呼叫 UDP.parsePacket()
,否则 read()
的呼叫会失败。
语法
Udp.read();
Udp.read(packetBuffer, MaxSize);
参数
packetBuffer
:用来存放读取资料的阵列,型态为 char
MaxSize
:packetBuffer
的大小,型态为 int
回传
char
:回传透过 UDP 接收到的资料
范例
#include <Ethernet.h> #include <EthernetUdp.h> // 输入本地端的 IP 位址 IPAddress ip(192, 168, 1, 177); // 要监听的本地端埠编号 unsigned int localPort = 8888; // 创建一个 EthernetUDP 物件,我们可以藉由这个物件收发 UDP 的封包 EthernetUDP Udp; // 要拿来存放资料的阵列 char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; void setup() { // 开始 Ethernet 和 EthernetUDP Ethernet.begin(NULL,ip); Udp.begin(localPort); } void loop() { int packetSize = Udp.parsePacket(); if(packetSize) { Serial.print("Received packet of size "); Serial.println(packetSize); Serial.print("From "); IPAddress remote = Udp.remoteIP(); for (int i =0; i < 4; i++) { Serial.print(remote[i], DEC); if (i < 3) { Serial.print("."); } } Serial.print(", port "); Serial.println(Udp.remotePort()); // 读取透过 UDP 接收到的资料并且放到 packetBuffer Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); Serial.println("Contents:"); Serial.println(packetBuffer); } }
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.