如何判断Socket是否断开

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;
}

你可能感兴趣的:(socket,server,服务器,null,buffer,byte)