linux阻塞套接字读取返回0字节但连接未断开

时间:2016-11-27 13:02:24

标签: c++ linux sockets

我正在测试linux tcp socket的行为,服务器套接字从不关闭并保持循环发送字符串到客户端,并且客户端读取字符串,但是,我发现它连接客户端read()返回0字节将没有数据到达。我有搜索stackoverflow类似的问题,但所有的答案告诉“读取返回0字节的阻塞套接字意味着服务器已断开连接”,我很困惑,因为我的测试代码,服务器永远不会关闭套接字,netstat也显示以ESTABLISHED模式连接。 以下是我的一些测试代码:

服务器代码:

if((new_fd=accept(listenfd,(struct sockaddr *)(&client_addr),&sin_size))== int(-1))
{
    exit(1);
}

int i=0;
while(1)
{
    //never ending loop
    char buf[20] = {0};
    sprintf(buf,"packet %d\n",i++);
    if(write(new_fd,buf,strlen(buf))==-1)
    {
        cout<<"write error"<<strerror(errno)<<endl;
        break;
    }
    sleep(5);
}
close(new_fd);
close(listenfd);

客户代码:

while(1) {
    //never ending loop
    int  ret = read(sock_cli, recvbuf, sizeof(recvbuf));
    if(ret==-1)
    {   
        cout<<"recv failed. err="<<strerror(errno)<<endl;
        break;
    }   
    else if(ret==0) {
        cout<<"recv completed. err="<<strerror(errno)<<endl;
        sleep(1);
        continue;
    }   
    else
    {   
        recvbuf[ret] = 0;
        fputs(recvbuf, stdout);
        continue;
    }   
} 

客户端保持输出如下:

packet 55
recv completed. err=Success
recv completed. err=Success
recv completed. err=Success
recv completed. err=Success
recv completed. err=Success
packet 56
recv completed. err=Success
recv completed. err=Success
recv completed. err=Success
recv completed. err=Success
recv completed. err=Success
packet 57
recv completed. err=Success
recv completed. err=Success
recv completed. err=Success
recv completed. err=Success
recv completed. err=Success
packet 58
recv completed. err=Success

知道为什么客户端在读取时没有阻塞但返回0?

0 个答案:

没有答案