阻塞模式下socket连接connect超时后长达75秒,如何避免

来源:互联网 发布:吴江js华腾公寓自提柜 编辑:程序博客网 时间:2024/06/08 11:03

一句话总结:设置非阻塞,用select等待一段时间看是否连接成功,连接成功再设回阻塞模式。

注意select第一个参数一定要加1,否则描述符刚好不在集合当中,会出现超时返回0不可读不可写但send、recv正常的情况。

先看实例再看select定义


server:

#include <iostream>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <unistd.h>#include <stdio.h>#include <string.h>using namespace std;int main(){struct sockaddr_in serAddr;int listenSock, cnntSock;listenSock = socket(AF_INET, SOCK_STREAM, 0);serAddr.sin_family = AF_INET;serAddr.sin_addr.s_addr = INADDR_ANY;serAddr.sin_port = htons(1270);bind(listenSock, (const struct sockaddr *)&serAddr, sizeof(sockaddr_in));listen(listenSock, 10);struct timeval tv = {3,0};//3s 超时setsockopt(listenSock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));struct sockaddr_in cliAddr;socklen_t len = sizeof(sockaddr_in);while (1){        memset(&cliAddr, 0, sizeof(cliAddr));cout << "wait accept..." << endl;cnntSock = accept(listenSock, (struct sockaddr*)&cliAddr, &len);        if (0 == cliAddr.sin_port)            continue;cout<< "IP:" <<inet_ntoa(cliAddr.sin_addr) <<", port:"<<cliAddr.sin_port<<endl;unsigned int total = 0;int cnt = 0;                while(1){            send(cnntSock, "hello", 6, 0);            cout <<"read msg..."<<endl;char buf[6000] = {0};int ret = recv(cnntSock, buf, sizeof(buf), 0); //wait 3 secif (-1 == ret)break;total += ret;cout << "msg:" <<endl;cout << buf;cout << "recv msg size:" << ret << ",total size:" << total <<endl;cnt++;                        if (2==cnt)break;}cout << "close connect..." << endl;close(cnntSock);}close(listenSock);return 0;}


client:

#include <iostream>#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <unistd.h>#include <fcntl.h>#include <unistd.h>using namespace std;int main()  {      int sockClient = socket(AF_INET, SOCK_STREAM, 0);      struct sockaddr_in addrSrv;      addrSrv.sin_addr.s_addr = inet_addr("127.0.0.1");      addrSrv.sin_family = AF_INET;      addrSrv.sin_port = htons(1270);     struct timeval tv = {3,0};//3s 超时    setsockopt(sockClient, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(struct timeval));     int flag = fcntl(sockClient, F_GETFL, 0);    flag |= O_NONBLOCK;    fcntl(sockClient, F_SETFL, flag);    int ret = connect(sockClient, ( const struct sockaddr *)&addrSrv, sizeof(struct sockaddr_in));      printf("ret:%d\n", ret);    fd_set rfd, wfd;    FD_ZERO(&rfd);    FD_ZERO(&wfd);    FD_SET(sockClient, &rfd);    FD_SET(sockClient, &wfd);    ret = select(sockClient+1, &rfd, &wfd, NULL, &tv);    printf("ret:%d\n", ret);    sleep(3);    if (FD_ISSET(sockClient, &rfd))    {        char buf[1024] = {0};        recv(sockClient, buf, 1024, 0);        printf("recv:%s\n", buf);        printf("sock is readable\n");    }    else    {        char buf[1024] = {0};        recv(sockClient, buf, 1024, 0);        printf("recv:%s\n", buf);        printf("sock is not readable\n");    }    if (FD_ISSET(sockClient, &wfd))        printf("sock is writable\n");    else    {        printf("sock is not writable\n");    }    flag = fcntl(sockClient, F_GETFL, 0);    flag &= ~O_NONBLOCK;    fcntl(sockClient, F_SETFL, flag);    char buf[10] = {0};      for(unsigned int i = 0; i < 10; i++)     {          buf[i] = 'd';       }           ret = send(sockClient, buf, sizeof(buf) , 0);       cout << "buf size:" << sizeof(buf) << ",ret:" << ret <<endl;    close(sockClient);        return 0;  }  

1、客户端判断fd是否可读可写之前不加延时3秒

zjy@ubuntu:~$ ./client 

ret:-1

ret:1

recv:

sock is not readable

sock is writable

buf size:10,ret:10

zjy@ubuntu:~$


select返回结果为1,只可写不可读

2、客户端判断fd是否可读可写之前加延时3秒

zjy@ubuntu:~$ ./server 

wait accept...

IP:127.0.0.1, port:56006

read msg...

msg:

ddddddddddrecv msg size:10,total size:10

read msg...

msg:

recv msg size:0,total size:10

close connect...

wait accept...

wait accept...

^C

zjy@ubuntu:~


zjy@ubuntu:~$ ./client 

ret:-1

ret:2

recv:hello

sock is readable

sock is writable

buf size:10,ret:10

recv:hello

sock is readable

zjy@ubuntu:~


select返回值为2,fd可读可写


下面select相关定义摘自于:http://www.cnblogs.com/wenqiang/p/5508541.html

select一般用在socket网络编程中,在网络编程的过程中,经常会遇到许多阻塞的函数,网络编程时使用的recv, recvfrom、connect函数都是阻塞的函数,当函数不能成功执行的时候,程序就会一直阻塞在这里,无法执行下面的代码。这是就需要用到非阻塞的编程方式,使用 selcet函数就可以实现非阻塞编程。
selcet函数是一个轮循函数,即当循环询问文件节点,可设置超时时间,超时时间到了就跳过代码继续往下执行

  select(),确定一个或多个套接口的状态,本函数用于确定一个或多个套接口的状态,对每一个套接口,调用者可查询它的可读性、可写性及错误状态信息,用fd_set结构来表示一组等待检查的套接口,在调用返回时,这个结构存有满足一定条件的套接口组的子集,并且select()返回满足条件的套接口的数目。

  通常采用select实现多路复用,也就是说可以同时监听多个文件描述符;

下面是select的函数原型:

1   /* According to POSIX.1-2001 */2  #include <sys/select.h>3  4  int select(int nfds, fd_set *readfds, fd_set *writefds,5                fd_set *exceptfds, struct timeval *timeout);

下面进行具体的解释:

第一个参数:int nfds--->是一个整数值,是指集合中所有文件描述符的范围,即所有文件描述符的最大值加1

第二个参数:fd_set *readfds---->用来检查一组可读性的文件描述符

第三个参数:fd_set *writefds---->用来检查一组可写性的文件描述符

第四个参数:fd_set *exceptfds---->用来检查文件文件描述符是否异常

第五个参数:sreuct timeval *timeout--->是一个时间结构体,用来设置超时时间

timeout:最多等待时间,对阻塞操作则为NULL

select函数的返回值 
负值:select错误
正值:表示某些文件可读或可写
0:等待超时,没有可读写或错误的文件

下面是一些跟select一起使用的函数及结构的作用

1 void FD_CLR(int fd, fd_set *set);//清空一个文件描述符的集合2 int  FD_ISSET(int fd, fd_set *set);//将一个文件描述符添加到一个指定的文件描述符集合中3 void FD_SET(int fd, fd_set *set);//将一个给定的文件描述符从集合中删除;4 void FD_ZERO(fd_set *set);//检查集合中指定的文件描述符是否可以读写

struct timeval结构是用来设置超时时间的,该结构体可以精确到秒跟毫秒

1  struct timeval {2         time_t         tv_sec;     /* seconds */3          suseconds_t    tv_usec;    /* microseconds */4 };



阅读全文
0 0