Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1015599
  • 博文数量: 244
  • 博客积分: 6820
  • 博客等级: 准将
  • 技术积分: 3020
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-09 21:33
文章分类

全部博文(244)

文章存档

2013年(1)

2012年(16)

2011年(132)

2010年(3)

2009年(12)

2008年(80)

我的朋友

分类: LINUX

2011-04-29 15:05:20

 Socket在连接以后,如果客户端非正常退出,比如网线掉了、超时退出等,服务器端的socket仍然有缓存,此时可以从该socket描述符中读出一些数据,短时间内甚至可以写,因此判断TCP socket是否断开及其不易,网上有很多方法,都不能精确判断。本人用select和recv写了一个,在缓冲区被读完以后判断非常管用。这里,recv时使用MSG_PEEK参数,数据不会从缓冲区中清除掉,因此不会影响正常的读写。
/* check whether socket is connected. Actually, it is not accurate if the client
 * crashs and the server don't know about it because the socket buffer is ready.
 * So the return value '0' doesn't mean the socket is really valid. Of course,
 * '-1' shows the socket is invalid
*/
int checksock(int s)
{
        fd_set   fds;
        char buf[2];
        int nbread;
        FD_ZERO(&fds);
        FD_SET(s,&fds);
        if ( select(s+1, &fds, (fd_set *)0, (fd_set *)0, NULL) == -1 ) {
                //log(LOG_ERR,"select(): %s\n",strerror(errno)) ;
                return -1;
        }
        if (!FD_ISSET(s,&fds)) {
                //log(LOG_ERR,"select() returns OK but FD_ISSET not\n") ;
                return -1;
        }      
        /* read one byte from socket */
        nbread = recv(s, buf, 1, MSG_PEEK);
        if (nbread <= 0)
                return -1;
        return 0;
}

阅读(2699) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~