我正在尝试编写服务器客户端代码,但我被困在了一个点上。我希望客户端阅读一定的时间和超时。我尝试使用 setsockopt() 和 SO_RCVTIMEO 指定 timeval 结构中的时间,但我的 read() 不等待我在 timeval 结构中指定的时间。问题是,如果我只是在 setsockopt() 之后使用 read(),read() 正在等待指定的时间。如果我先调用 write() 然后 read(),read() 函数会立即超时,而无需等待 timeval 结构中给出的指定时间。我的代码如下所示:
//示例客户端代码
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int a=1;
fd_set readfds,writefds;
int ready_for_reading,reading;
struct timeval time_out;
int sockfd,newsockfd,portno,n;
struct sockaddr_in serv_addr;
struct hostent *server;
// server=gethostbyname(argv[1]);
char buffer[256];
portno=atoi(argv[2]);
sockfd=socket(AF_INET,SOCK_STREAM,0);
server=gethostbyname(argv[1]);
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(portno);
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
time_out.tv_sec = 15; // 15 seconds
time_out.tv_usec = 0; // 0 milliseconds
// sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
error("\nError creating socket");
// if(setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&time_out, sizeof (time_out)))
// error("\n\tsetsockopt function has a problem\n");
n=connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
if(n==-1)
error("\nError connecting to server");
printf("\nEnter client's msg:");
fgets(buffer,255,stdin);
n=write(sockfd,buffer,strlen(buffer));
if(n<0)
error("\nMsg not written to server");
if(setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&time_out, sizeof(time_out)))
error("\n\tsetsockopt function has a problem\n");
// FD_ZERO(&readfds);
// FD_SET(sockfd,&readfds);
n=read(sockfd,buffer,255);
// ready_for_reading=select(sockfd,&readfds,NULL,NULL,&time_out);
// printf("\nready_for_reading=%d",ready_for_reading);
/* if (ready_for_reading)
{
// reading = read(newsockfd, buffer, 255);
printf("Read, %d bytes from input : %s \n", n,buffer);
}
else
{
printf(" 10 Seconds are over - no data input \n");
return 0;
}
*/
if(n<0)
printf("\nMsg not read from server");
if(n==0)
{
printf("\n No ack from server");
return 0;
}
printf("\nServer's ack:%s\n",buffer);
/* if (ready_for_reading)
{
// reading = read(newsockfd, buffer, 255);
printf("Read, %d bytes from input : %s \n", n,buffer);
}
else
{
printf(" 10 Seconds are over - no data input \n");
return 0;
}
*/
return 0;
}
在我上面的代码中,我希望 read() 操作在 15 秒内超时。但它立即超时。我需要帮助!!!