我有一个扭曲的服务器,它做了一些事情然后关闭了连接。 python客户端理解
clientConnectionLost(self, connector, reason)
连接已关闭并且工作正常。 但是,我还有一个 C++ 客户端与同一个扭曲的服务器通信。目前似乎不明白连接/套接字已关闭。我该如何检查?
string tcp_client::receive(int size=1024)
{
char buffer[size];
string reply;
int msg = recv(sock , buffer , sizeof(buffer) , 0);
// Receive a reply from the server
if(msg < 0)
{
puts("recv failed");
// Exit the programm
exit(0);
}
reply = buffer;
return reply;
}
是C++客户端的接收码。 如何使用 C++ 客户端实现与 clientConnectionLost 相同/相似的功能?
最佳答案
来自 man recv :
The return value will be 0 when the peer has performed an orderly shutdown.
所以在 recv
调用之后,你可以这样写:
string tcp_client::receive(int size=1024)
{
char buffer[size];
string reply;
// Receive a reply from the server
int msg = recv(sock , buffer , sizeof(buffer) , 0);
if(msg < 0)
{
puts("recv failed");
// Exit the programm
exit(0);
}
else if (0 == msg)
{
// the connexion has been closed by server
puts("Connexion lost!");
// close the socket
close(sock);
// return something
return string("");
}
reply = buffer;
return reply;
}
关于C++ 客户端需要找出套接字被扭曲的服务器关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36982067/