1
我正在用ESP32(一個很好的平臺btw)構建一個分佈式應用程序,所有參與者都應該以最簡單的形式通過UDP進行通信:通過廣播發送消息並收聽所有消息漂浮在左右。每個參與者自行過濾相關消息。ESP32 - 帶本地LwIP庫的UDP廣播器/接收器
到目前爲止,我有以下的初始化程序:
int lavor_wifi_openUDPsocket(){
// Create a socket
int sckt = socket(AF_INET, SOCK_DGRAM, 0);
if (sckt < 0){
printf("socket call failed");
exit(0);
}
// Prepare binding to port
struct sockaddr_in sLocalAddr;
// Initialize the address
memset((char *)&sLocalAddr, 0, sizeof(sLocalAddr));
sLocalAddr.sin_family = AF_INET;
sLocalAddr.sin_len = sizeof(sLocalAddr);
sLocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);
sLocalAddr.sin_port = UDP_SOCKET_PORT;
bind(sckt, (struct sockaddr *)&sLocalAddr, sizeof(sLocalAddr));
return sckt;
}
然後,一條消息將與被髮送:
void lavor_wifi_sendUDPmsg(int sckt, char* msg, int len){
// Prepare the address to sent to via BROADCAST
struct sockaddr_in sDestAddr;
// Initialize the address
// memset((char *)&sDestAddr, 0, sizeof(sDestAddr));
sDestAddr.sin_family = AF_INET;
sDestAddr.sin_len = sizeof(sDestAddr);
sDestAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
sDestAddr.sin_port = UDP_SOCKET_PORT;
if(sendto(sckt, msg, len, 0, (struct sockaddr *)&sDestAddr, sizeof(sDestAddr)) < len){
printf("UDP message couldn't be sent.");
}
}
最後,接收消息會像這樣工作:
void lavor_wifi_processor(void* sckt){
int nbytes;
char buffer[UDP_BUFF_LEN];
// Listen for incoming messages as long as the socket is open
while(1){ // TO DO: Test if socket open
// Try to read new data arrived at the socket
nbytes = recv(*((int *)sckt), buffer, sizeof(buffer), 0);
...
但即使我只是試圖調用上面的初始化函數,ESP變得瘋狂了nd拋出一個Guru冥想錯誤。
有沒有人有經驗的UDP通信的描述方式?