我正在尝试实现一个具有1秒接收超时的套接字:
int sockfd;
struct sockaddr_in self;
struct sockaddr_in client_addr;
int addrlen=sizeof(client_addr);
ssize_t nBytes;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
self.sin_family = AF_INET;
self.sin_port = htons(PORT);
self.sin_addr.s_addr = INADDR_ANY;
int on = 1;
setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on);
// 1 Sec Timeout
tv.tv_sec = 1;
tv.tv_usec = 0;
setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv);
bind(sockfd, (struct sockaddr*)&self, sizeof(self));
listen(sockfd, 20);
clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
nBytes = recv(clientfd, buffer, MAXBUF-1, 0);
没有设置 setsockopt (sockfd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv);,accept 和 recv 的调用可以工作,但 recv 会阻塞。
使用setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));时,对accept的调用会产生错误“资源暂时不可用”。
有人能告诉我这种方法有什么问题吗?