NodeMCU网络UDP客户端请求,示例代码(C++开发)

【NodeMCU网络UDP客户端请求,示例代码(C++开发)】用NodeMCU作为udp客户端访问udp服务端得c++代码。

#include #include //定义全局量 const char* ssid= "xxx"; const char* password= "xxxxxx"; //Udp param WiFiUDP Udp; unsigned int localUdpPort = 2333; // 本地端口号 char incomingPacket[537]; // 接收缓冲区void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); }//init udp UdpInit(); UdpSend(); }void UdpInit() { //https://www.arduino.cc/en/Reference/WiFi //以下开启UDP监听并打印输出信息 Udp.begin(localUdpPort); Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort); }void UdpSend() { Udp.beginPacket("device.xxx.com", 9090); Udp.write("LED has been turn off"); // 回复LED has been turn off Udp.endPacket(); } void UdpRecv() { int packetSize = Udp.parsePacket(); //获取当前队首数据包长度 if (packetSize)// 有数据可用 { Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort()); int len = Udp.read(incomingPacket, 536); // 读取数据到incomingPacket if (len > 0)// 如果正确读取 { incomingPacket[len] = 0; //末尾补0结束字符串 Serial.printf("UDP packet contents: %s\n", incomingPacket); } } }void loop() { UdpRecv(); }


    推荐阅读