【ESP8266】 UDP服务器

本代码主要实现了,监听一个UDP端口,并且在收到消息后,向发送端返回一个Hello字符串

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "xxxxxx";
const char* password = "xxxxx";

WiFiUDP Udp;
unsigned int localUdpPort = 4210; 
char incomingPacket[255];  
char  replyPacket[] = "Hi there! Got the message :-)"; 


void setup()
{
  Serial.begin(9600);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
//开始UDP监听
  Udp.begin(localUdpPort);
  Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);
}
void loop()
{
  int packetSize = Udp.parsePacket();
  if (packetSize)//解析包不为空
  {
    Serial.printf("收到来自远程IP:%s(远程端口:%d)的数据包字节数:%d\n", Udp.remoteIP().toString().c_str(), Udp.remotePort(), packetSize);
    String udpStringVal = Udp.readString(); 
    Serial.print("开发板接收到UDP数据中的字符串 "); Serial.println(udpStringVal);
    //向udp工具发送消息
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());//配置远端ip地址和端口
    Udp.write("Hello");//把数据写入发送缓冲区
    Udp.endPacket();//发送数据
  }
}
posted @ 2022-04-11 19:27  Mudrobot  阅读(260)  评论(0编辑  收藏  举报