gpt4 book ai didi

c++ - linux C/C++ socket程序为什么不出现ECONNRESET错误

转载 作者:行者123 更新时间:2023-11-30 20:14:00 25 4
gpt4 key购买 nike

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

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() 预计将开始返回零(当然,只有在它完成返回服务器 send() 处理的任何数据之后)

关于c++ - linux C/C++ socket程序为什么不出现ECONNRESET错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28144555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com