当我注释掉关闭阻止一切正常的代码时,但是当我离开非阻塞代码时,我从来没有从recvfrom获得任何数据。 (接收的字节总是0)这是带有阻塞语句的代码。我是Xcode和IOS的新手,但是已经为.NET创建了UDP代码。
// Create Socket
int Handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (Handle <=0){
printf("Failed to create socket\n");
}
// Bind Socket
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons((unsigned short) 4966);
if (bind(Handle,(struct sockaddr *) &address, sizeof(struct sockaddr_in))< 0){
printf("Failed to Bind\n");
}//end if
printf("Bind Done\n");
// Set to non Blocking
int NonBlocking = 1;
//if (fcntl(Handle, F_SETFL, O_NONBLOCK, NonBlocking) == -1){
printf("Faile to set nonblocking\n");
//}
Boolean ContinueLoop = true;
unsigned char Packet_Data[256];
unsigned int Maximum_Packet_Size = sizeof(Packet_Data);
struct sockaddr_in From_Address;
socklen_t FromLength = sizeof(From_Address);
while (ContinueLoop){
int Received_Bytes = recvfrom(Handle, (char *)Packet_Data, Maximum_Packet_Size, 0, (struct sockaddr *)&From_Address, &FromLength);
if (Received_Bytes > 0){
ContinueLoop = false;
printf("Got Data \n");
} else {
perror("Now");
printf(".");
}
close(Handle);
}//wend
答案 0 :(得分:0)
发现问题。我不小心在while循环中包含了close语句。将它移出它所属的循环,现在一切正常。阻止和非阻塞。