基本概念:
其实UDP的非阻塞也可以理解成和TCP是一样的,都是通过socket的属性去做。
方法一:通过fcntl函数将套接字设置为非阻塞模式。
方法二:通过套接字选项SO_RECVTIMEO设置超时。
方法一源码,编译:g++ udp_server.cpp -o server
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <strings.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
void Perror(const char *s)
{
perror(s);
exit(EXIT_FAILURE);
}
//设置非阻塞
static void setnonblocking(int sockfd) {
int flag = fcntl(sockfd, F_GETFL, 0);
if (flag < 0) {
Perror("fcntl F_GETFL fail");
return;
}
if (fcntl(sockfd, F_SETFL, flag | O_NONBLO