在我的程序中,如果无法访问服务器,则连接功能需要太多时间。所以我尝试使用 select() 给时间连接。现在的问题是,当我尝试使用 recvfrom() 从服务器接收数据时,出现错误“EAGAIN”。这是用于连接和接收来自服务器的数据的代码。
int sock;
struct sockaddr_in addr;
int connectWithServer
{
int status;
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
addr.sin_port = htons(port);
sock = socket (AF_INET,SOCK_STREAM,0);
inet_pton(AF_INET,serverIP,&addr.sin_addr);
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
fcntl(sock, F_SETFL, O_NONBLOCK);
if ( (status = connect(sock, (struct sockaddr*)&addr, sizeof(addr))) == -1)
{
if ( errno != EINPROGRESS )
return status;
}
status = select(sock+1, NULL, &set, NULL, &timeout);
return status;
}
long int receiveResponse (void *response , unsigned int length)
{
socklen_t sockLen = sizeof(struct sockaddr);
long int received = recvfrom(sock, response, length, 0,(struct sockaddr *)&addr, &sockLen);
printf("Received %ld bytes... err %d\n",received, errno);
return received;
}