注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

守望

路越远,心越近。有多远,走多远!

 
 
 

日志

 
 

TCP连接的非阻塞处理  

2011-12-18 10:04:04|  分类: 编程 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

         h->connect_status = 0;

         h->connect_starttime = time(NULL);

         if(connect(h->fd, (struct sockaddr *)&h->server, sizeof(struct sockaddr_in)) < 0)

         {

                   perror("connect failed:");           

                   if (errno != EALREADY && errno != EINPROGRESS)

                   {

                            perror("Connect Server failed:");

                            close(h->fd);

                            h->connect_status = 0;

                            h->fd = -1;

                            return -1;

                   }

                   //usleep(1000000);

                   //printf("call usleep(1000000)\n");

                  

                   FD_ZERO(&writeset);

                   FD_SET(h->fd, &writeset);

                   tv.tv_sec = 0;

                   tv.tv_usec = 500000;

                   if(select(h->fd + 1, NULL, &writeset, NULL, &tv) > 0)

                   {

                            opt_len = sizeof(connect_status);

                            ret = getsockopt(h->fd, SOL_SOCKET, SO_ERROR, (char *)&connect_status, &opt_len);

                            if(ret == 0)

                            {

                                     if(connect_status == 0)

                                     {

                                               printf("connect ok.\n");

                                     }

                                     else

                                     {

                                               printf("socket status:%d\n", strerror(connect_status));

                                               h->connect_status = -1; //connect_status;

                                               return -1;

                                     }

                            }

                   }

                   else

                   {

                            perror("select failed:");

                            h->connect_status = -1;

                            return -1;

                   }

         }



  评论这张
 
阅读(987)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017