gpt4 book ai didi

c 如何结束套接字读取

转载 作者:行者123 更新时间:2023-11-30 17:03:13 26 4
gpt4 key购买 nike

我正在尝试读取服务器,直到客户端发送完成消息。这是 myVar.id==-1。我在服务器中无限循环地读取,直到它从客户端读取完成标志。它会一直读取,直到收到客户端的完成标志,但它并没有结束,而是卡在那里。有什么想法吗?

//server

sockdesc = socket(AF_INET, SOCK_STREAM, 0);
if ( sockdesc < 0 )
{
cout << "Error creating socket" << endl;
exit(0);
}
else{
if ( getaddrinfo("0.0.0.0", portnum, NULL, &myinfo) != 0 )
{
cout << "Error getting address" << endl;
exit(0);
}
}
if (bind(sockdesc, myinfo->ai_addr, myinfo->ai_addrlen) < 0 ){
cout << "Error binding to socket" << endl;
exit(0);
}
if ( listen(sockdesc, 1) < 0 ){
cout << "Error in listen" << endl;
exit(0);
}
connection = accept(sockdesc, NULL, NULL);
if ( connection < 0 ){
cout << "Error in accept" << endl;
exit(0);
}
while(true){
value = read(connection, (char*)&myVar, sizeof(procd));
if (value < 0) {
perror("ERROR reading from socket");
exit(1);
}
if(myVar.id==-1){
close(connection);
exit(0);
}//if
else{
//display what received

}
}

//client
while ( getline (inputFile,line) )//read a line till EOF
{
write(sockdesc, (char*)&myVar, sizeof(procd));
}
myVar.id=-1;
write(sockdesc, (char*)&myVar, sizeof(procd));

最佳答案

你还必须处理你的客户可能意外死亡的情况.........在这种情况下,READ 将返回零...

虽然你没有说明你正在使用什么平台,但 Linux 上的手册页说: 如果 fildes 引用套接字,则 read() 应等效于没有设置标志的 recv()。

recv() 的手册页说:

Return Value

Upon successful completion, recv() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

您的代码无法处理 read 返回零的特殊情况。

关于c 如何结束套接字读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36243745/

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