linux C/C++套接字程序为什么没有出现ECONNRESET错误

linux C/C++ socket program Why does not appear ECONNRESET error

本文关键字:ECONNRESET 错误 为什么 C++ 套接字 程序 linux      更新时间:2023-10-16

服务器端子功能:recv 客户端数据,然后关闭套接字

server side child func:
                char line[1024];
                bzero(line,sizeof(line));
                int ret =  recv(fd,line,sizeof(line),0);
                if(ret > 0){
                        cout << line << endl;
                }else if(ret < 0){
                        cout << "recv error" << endl;
                }else if(ret == 0){
                        cout << "client close" << endl;
                        break;
                }
                shutdown(fd,SHUT_WR);

客户端主函数

char line[] = "ds2d2d2d2d21dwq";
        send(sockfd,line,sizeof(line),0); //send to server
        //server side the child func has exit
        sleep(20);
        cout << "write to server" << endl;
        //write to server again
        ret = send(sockfd,line,sizeof(line),0);
        perror("write...."); //write success
        //according to unp book ,the server has send the RST msg to client
        bzero(line,sizeof(line));
        sleep(5);
        //recv should return error and the error code should ECONNRESET 
        //but not appear , the recv success return 0(EOF)
        //then execute recv success return 0(EOF)
        ret = recv(sockfd,line,sizeof(line),0);
        cout << ret <<line << endl;
        perror("recv....");
        ret = recv(sockfd,line,sizeof(line),0);
        perror("recv....");

我不知道对吗?内核改进。我发现 recv 系统没有 ECONNRESET 错误代码

从"man recv"页面:

RETURN VALUES
  These calls return the number of bytes received, or -1 if an error
  occurred.
  For TCP sockets, the return value 0 means the peer has closed its half
  side of the connection.

因此,当服务器关闭TCP连接时,预计客户端上的recv()将开始返回零(当然,只有在它完成返回服务器发送()的任何数据之后)

这里没有任何内容会引发重置。在读取所有数据后,您应该在客户端中获取来自recv()的零返回值。您的期望不正确。

其他问题:

  • "内核改进"是什么意思?
  • 当您不知道是否存在错误时,您在客户端中调用perror()。只有在系统调用返回 -1 之后,才应该直接调用它。
  • 当您知道这一点时,您不会在服务器中调用它。