int nNetTimeout=1000;//1秒,
//设置发送超时
setsockopt(socket,SOL_SOCKET,SO_SNDTIMEO,(char *)&nNetTimeout,sizeof(int));
//设置接收超时
setsockopt(socket,SOL_SOCKET,SO_RCVTIMEO,(char *)&nNetTimeout,sizeof(int));
//设置发送超时
setsockopt(socket,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(struct timeval));
setsockopt(socket,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout,sizeof(struct timeval));
2)即使等待超时时间值未到,但对方已经关闭了socket, 则此时recv()会立即返回,并收到多少数据返回多少数据。
====
http://blog.youkuaiyun.com/newger/article/details/2459113
----
-
SO_RCVTIMEO and
SO_SNDTIMEO
- Specify the receiving or sending timeouts until reporting an error. The argument is a struct timeval. If an input or output function blocks for thisperiod of time, and data has been sent or received, the return value of that function will be the amount of data transferred; if no data has been transferredand the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK just as if the socket was specified to benonblocking. If the timeout is set to zero (the default) then the operation will never timeout. Timeouts only have effect for system calls that perform socketI/O (e.g., read(2), recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for select(2), poll(2), epoll_wait(2), etc. ====
-
The timeval structure is used to specify a time interval. It is associated with the Berkeley Software Distribution (BSD) Time.h header file.
Syntax
typedef struct timeval {
long tv_sec;
long tv_usec;
} timeval;
Members
-
tv_sec
-
Time interval, in seconds.
tv_usec
-
Time interval, in microseconds. This value is used in combination with the tv_sec member to represent time interval values that are not a multiple of seconds.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms740560%28v=vs.85%29.aspx
本文详细介绍了在Linux环境下如何正确地为socket设置发送和接收超时,避免因网络状况导致的数据收发失败。文中强调了使用struct timeval来定义超时时间的重要性,并解释了recv()函数的行为变化。
3955

被折叠的 条评论
为什么被折叠?



