【问题标题】:linux C/C++ socket program Why does not appear ECONNRESET errorlinux C/C++ socket程序为什么不出现ECONNRESET错误
【发布时间】:2015-01-26 03:48:08
【问题描述】:

服务器端子函数:接收客户端数据,然后关闭套接字

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错误代码

【问题讨论】:

  • 对错误使用perrorstrerror

标签: c++ c linux sockets


【解决方案1】:

来自“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() 将开始返回零(当然,只有在它完成返回服务器发送的任何数据之后)

【讨论】:

  • 谢谢,但我还有另一个问题,为什么 read/recv 系统调用 man doc 没有 ECONNRESET 错误代码? unp book 有错误代码
【解决方案2】:

这里没有任何东西会引发重置。在您读取所有数据之后,您应该在客户端中获得来自recv() 的零返回值。你的预期是错误的。

其他问题:

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

【讨论】:

  • @downvoter 请向我们解释 OP 代码中会引发重置的内容,或者您​​对此答案还有什么其他问题。
  • 我承认这是一个糟糕的问题描述,但不要在答案区抱怨。如果您愿意,请投票否决这个问题。如果您想回答,请回答一些有意义的问题。
  • @juji 我不明白你的意思。如果这个问题没有意义,你为什么要自己回答?如果你声称这个答案没有意义,或者完全由“投诉”组成,那你就错了。阅读第一段。
  • 我没有说the question isn't meaningful,我说它有a bad question description
  • @juji 那么您对这个答案的反对究竟是什么?你说了一些关于“回答有意义的事情”的令人费解的话,我正试图解开。 是什么意思
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
相关资源
最近更新 更多