我正在使用 ESP32(顺便说一句,一个很棒的平台)构建一个分布式应用程序,所有参与者都应该以最简单的形式通过 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 也会变得疯狂并引发一个又一个 Guru Meditation 错误。
有没有人以所描述的方式进行 UDP 通信?