【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();
}
推荐阅读
- NodeMCU(1)环境搭建与固件烧录
- NodeMCU的smartConfig功能代码实现手机app配置模块连接网络(C++开发)
- 物联网|NodeMcu—局域网通信
- 编程语言|关于NodeMCU的内存测试
- NodeMCU--MQTT学习笔记(一)
- 硬件|从无到有玩NodeMcu(web端控制)
- 使用nodemcu玩转物联网系列(二)(nodemcu做为station模式连接无线路由器)
- ESP8266|NodeMCU介绍
- NodeMCU|NodeMCU入门,烧程序点灯。