1

In my program i am using timeval structure of time.h for a TCP/IP socket program, in which the client waits for a timeout value as specified by this structure value the structure initialization is as below

struct timeval tv; 
tv.tv_sec  = 10;  
tv.tv_usec = 0; 

and setting socket options as is. Since recv() is a blocking call I've put a timeout:

setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval)) ;

and receive data using recv() function. So to verify whether delay is ok I used two variables start & stop of type time_t:

time_t start=clock();
BytesRcvd = recv(sock, CacheBuffer1,  sizeof(CacheBuffer1), FLAG);
time_t stop=clock();
time_t difference=difftime(stop,start);

so as per the definitions what I expect is the recv() functions waits for maximum of 10 seconds until data is received via socket. From the server side I didn't send anything. But upon calculating the difference the value I've obtained is 10 but I didn't feel a 10 second delay for reception, but just in the range of milliseconds, so I assume it only took about 10 millisecond

What might be the issue?? Any thoughts?


[update from comment]

My socket is non-blocking that's why I used setsocketopt() function, and I want to wait for a timeout value of 10 Seconds ,ie; if within 10seconds no data is received I have to exit from the recv() function...

4

2 回答 2

4

如果您的套接字是非阻塞的recv(),即使您设置了超时,也不会阻塞。

设置超时对于阻塞套接字是有意义的,不会让它们永远阻塞。

因此,如果您希望recv()阻塞一段时间,请将套接字设置为阻塞像您一样应用超时。

于 2014-03-27T15:41:41.137 回答
0

你的时间计算是完全错误的

clock()计算在大多数平台上花费的 CPU 时间(Windows 是一个例外)。阻塞和等待数据不会消耗大量的 CPU 时间。

此外,clock()返回 a clock_t,而不是 a time_t,因此将其传递给difftime()没有意义。clock()也以 CLOCKS_PER_SEC 为单位,因此如果要将时间差转换为例如毫秒或秒,则需要考虑这一点。

首先,由于您的超时时间大约为几秒,请使用 time() 计算它们花费的时间,结果将以秒为单位。如果您需要更精细的东西,请使用例如gettimeofday()

time_t start=time();
BytesRcvd = recv(sock, CacheBuffer1,  sizeof(CacheBuffer1), FLAG);
time_t stop=time();
time_t difference=difftime(stop,start);
于 2014-03-27T17:18:31.727 回答