我正在编写一个小的网络实用程序,在我的代码中有以下几行:
if (connect(sock, addr_result->ai_addr, addr_result->ai_addrlen) < 0)
syserr("connect");我有两个关于超时的问题:
connect()设置超时?发布于 2015-04-28 07:58:54
为SIGALARM注册信号处理程序。在调用连接之前设置警报,在连接返回后清除警报,如果您按下信号处理程序,则连接超时。
发布于 2015-04-28 09:33:00
使用非阻塞连接,并使用select或轮询或epoll作为超时。这是样品。
int fd = socket(PF_INET,SOCK_STREAM,0);
int flags = fcntl(fd,F_GETFL);
if (flags >= 0)
flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
int n = connect(fd, (struct sockaddr*)&addr, sizeof addr);
if(n < 0)
{
if(errno != EINPROGRESS && errno != EWOULDBLOCK)
return 1;
struct timeval tv;
tv.tv_sec = 10;
tv.tv_usec = 0;
fd_set wset;
FD_ZERO(&wset);
FD_SET(fd,&wset);
n = select(fd+1,NULL,&wset,NULL,&tv);
if(n < 0)
{
close(fd);
return 1;
}
else if (0 == n)
{ // timeout
cerr<< "Timeout." << endl;
close(fd);
return 1;
}
else
{ // connect success
cerr << "Connectd." <<endl;
}
} 发布于 2015-04-28 08:28:00
将套接字设置为非阻塞,发出connect(),,然后使用select()、poll()或epoll()进行超时,选择可写性。
我不知道你所说的“测量超时时间”是什么意思。
https://stackoverflow.com/questions/29913483
复制相似问题