我有这样的Linux UDP
套接字代码:
//create the UDP socket and bind to a local port 5001
//sockfd = socket(AF_INET, UDP, 0);
//bind(sockfd, .., ...);
recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr *)&remote_addr, &addrlen);
printf("%s\n", buffer);
到此处,recvfrom
工作正常,上面的printf
可以打印我从ncat
客户端发送的内容。
但是,如果我在recvfrom
之后添加select()
,请参阅下面的代码,当我从select()
客户端向此套接字发送数据时,ncat
将不会返回。
max_fd = 0
FD_ZERO(&read_set);
FD_SET(sockfd, &read_set);
while (1) {
i = select(max_fd + 1, &read_set, NULL, NULL, NULL); //==> !!! select() is not returned from ncat sent data to this socket
if (i < 0 && errno != EINTR) {
.............
}
for (current_fd = 0; current_fd <= max_fd; current_fd++){
if ( !FD_ISSET(current_fd, &read_set) )
continue;
nbytes = recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr *)&remote_addr, &addrlen);
printf("%d bytes received \n", nbytes );
}
}
答案 0 :(得分:0)
while (1) {
FD_ZERO(&read_set);
FD_SET(sockfd, &read_set);
i = select(max_fd + 1, &read_set, NULL, NULL, NULL);
if (i < 0 && errno != EINTR) {
.............
}
for (current_fd = 0; current_fd <= max_fd; current_fd++){
if ( !FD_ISSET(current_fd, &read_set) )
continue;
nbytes = recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr *)&remote_addr, &addrlen);
printf("%d bytes received \n", nbytes );
}
}