Kora K Kora K - 4 months ago 15
Linux Question

C++ client needs to find out socket was closed by twisted server

I have a twisted server that does something and then closes the connection. The python clients understand with

clientConnectionLost(self, connector, reason)


that the connection was closed and that works fine.
However, I also have a C++ client communicating with the same twisted server. It currently doesn't seem to understand that the connection/socket was closed. How do I check for this?

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;
}


is the C++ client's receive code.
How do I reach the same/similar functionality of clientConnectionLost with the C++ client?

Answer

From man recv:

The return value will be 0 when the peer has performed an orderly shutdown.

So after recv call, you can write:

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;
}