EthernetUDP.read()

描述

讀取透過 UDP 接收到的資料。如果沒有給參數,會回傳待讀資料中的第一個資料。

要使用 read() 前必須先呼叫 UDP.parsePacket() ,否則 read() 的呼叫會失敗。

語法


Udp.read();
Udp.read(packetBuffer, MaxSize);

參數

packetBuffer:用來存放讀取資料的陣列,型態為 char
MaxSizepacketBuffer 的大小,型態為 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.